Home » Java » java – Spring: Using @Qualifier & @Profile-Exceptionshub

java – Spring: Using @Qualifier & @Profile-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a component class (let’s class in MyService) which is marked by @Qualifier(US).

As this component needed some values present in an application.yml file, I also marked the class with @Profile({"default", "qual"}) to get the correct values for some inner properties of the class.

Problem, when I execute cucumber tests for this specific qualifier (US), the program throws the following error An unexpected internal server error occurred: No bean named 'US' available: No matching MyService bean found for qualifier 'US' - neither qualifier match nor bean name match!

So, what I understand with this, it’s the annotations @Qualifier & @Profile don’t work together. Is that right? Or do I miss something to use both of them in the same class?

How to&Answers:

@Qualifer

This annotation may be used on a field or parameter as a qualifier for
candidate beans when autowiring.

@Profile

Indicates that a component is eligible for registration when one or
more specified profiles are active.

The class with following set of annotations

@Service
@Qualifier("US")
@Profile({"default", "qual"})
public class MyService {
...}

will only register the MyService bean when “default” or “qual” profiles are active and then on the bean can be autowired with the qualifier “US”

@Autowired
@Qualifer("US")
private MyService myService;

@Value can be used to inject the properties

@Value(${some.name})
private String name;