I have two beans that implements the same interface. Both are created in Java configuration, like this:
#Bean
#Qualifier("kafkaEventSender")
public IKafkaEventSender<KafkaData> kafkaEventSender(#Qualifier("EventBus") KafkaTemplate<String, Object> kafkaTemplate){
return new KafkaEventSender<>(kafkaTemplate, false);
}
#Bean
#Qualifier("kafkaEventSenderAudited")
public IKafkaEventSender<KafkaData> kafkaEventSenderAudited(#Qualifier("EventBus") KafkaTemplate<String, Object> kafkaTemplate){
return new KafkaEventSenderAudited<>(kafkaTemplate, false);
}
The problem is that spring doesn't create first bean only the second. Any idea why?
Try using bean names instead:
#Bean(name = "kafkaEventSender")
public IKafkaEventSender<KafkaData> kafkaEventSender(#Qualifier("EventBus") KafkaTemplate<String, Object> kafkaTemplate){
return new KafkaEventSender<>(kafkaTemplate, false);
}
#Bean(name = "kafkaEventSenderAudited")
public IKafkaEventSender<KafkaData> kafkaEventSenderAudited(#Qualifier("EventBus") KafkaTemplate<String, Object> kafkaTemplate){
return new KafkaEventSenderAudited<>(kafkaTemplate, false);
}
Ok, the problem was with method name, after changing it, bean is properly created. In some other library configuration class was a method with same name. Guessing that was the problem.
#Qualifier annotation is used to select one bean over multiple available beans of same type in spring container.
when you annotate a method with #Bean annotation, default, it creates a bean whose name is the name of same method. So, for example:
#Bean
public BeanA itsBeanA() {
return new BeanA();
}
#Bean(name = "specialBeanA")
public BeanA itsAgainBeanA() {
return new BeanA("specialConstructorParam");
}
#Bean
public BeanB beanB(#Autowired #Qualifier("specialBeanA") BeanA beanA) {
return new BeanB(beanA);
}
first method will create an instance of BeanA with name 'itsBeanA'. Second, will create an instance with name 'specialBeanA' since we provided the name attribute here.
There maybe a scenario where you need to have multiple beans of same TYPE (like BeanA here). It will create ambiguity for container which bean to use of all same types, we specify the #Qualifier with the name of bean which we want.
I hope that helps.
Related
Why do we use qualifiers with #Bean when we can have different names for different beans of the same type (class)?
#Bean
#Qualifier("fooConfig")
public Baz method1() {
}
Isn't the following code more clean?
#Bean("fooConfig")
public Baz method1() {
}
If I create two beans of the same type with different names (using #Bean annotation), then can we inject them specifically using the #Qualifier annotation(can be added on field/constructor parameter/setter) in another bean?
#Bean("fooConfig")
public Baz method1(){
}
#Bean("barConfig")
public Baz method2(){
}
// constructor parameter of a different bean
final #Qualifier("fooConfig") Baz myConfig
If the above is true, then where do we use #Qualifier (with #Bean or #Component) instead of giving the bean a name as shown below?
#Bean
#Qualifier("fooConfig")
public Baz method1(){
}
#Bean
#Qualifier("barConfig")
public Baz method2(){
}
// constructor parameter of a different bean
final #Qualifier("fooConfig") Baz myConfig
Beans have names. They don't have qualifiers. #Qualifier is annotation, with which you tell Spring the name of Bean to be injected.
No.
Default Qualifier is the only implementation of the interface(example is below, 4th question) or the only method with a particular return type. You don't need to specify the #Qualifier in that case. Spring is smart enough to find itself.
For example:
#Configuration
public class MyConfiguration {
#Bean
public MyCustomComponent myComponent() {
return new MyCustomComponent();
}
}
If you will try to inject myComponent somewhere, Spring is smart enough to find the bean above. Becaude there is only one Bean with return type MyCustomComponent. But if there was a couple of methods, that would return MyCustomComponent, then you would have to tell Spring which one to inject with #Qualifier annotation.
SIDENOTE: #Bean annotation by default Spring uses the method name as a bean name. You can also assign other name like #Bean("otherComponent").
You have one Interface, and a couple of Classes implementing it. You inject bean of your interface. How can Spring know which Class should be used?
This is you interface:
public interface TestRepository{}
This is your implementation 1:
#Repository
public class Test1Repository implements TestRepository{}
Your implementation 2:
#Repository
public class Test2Repository implements TestRepository{}
Now you are injecting it like:
private final TestRepository testRepository;
public TestServiceImpl(TestRepository testRepository) {
this.testRepository= testRepository;
}
QUESTION! How is Spring supposed to know which class to inject? Test1 or Test2? That's why you tell it with #Qualifier which class.
private final TestRepository testRepository;
public TestServiceImpl(#Qualifier("test1Repository") TestRepository testRepository) {
this.testRepository= testRepository;
}
I Prefer different method to not using #Qualifier
Create common Interface
public interface CommonFooBar{
public String commonFoo();
public String commonBar();
}
Extends to each service
public interface FooService extends CommonFooBar {
}
public interface BarService extends CommonFooBar {
}
Then using it to your class
#Autowired
FooService fooService;
or
#Autowired
BarService barService;
so, we can defined the single responsibility to each interface and This kind of segregation is more readable to every junior.
I quite like a different way of working. Surely if you provide a unique name for your bean, then that is all you need?
Given the example below, its easy to see that Spring will name the beans based on the method name used to create the beans. In other words, if you give your beans sensible names, then the code should become self-explanatory. This also works when injecting beans into other classes.
The end result of this is:
Spring will name your beans based on the method used to create them.
If you import a bean, Spring will try to match on the bean name.
If you try to import a bean that does not match the name, Spring will attempt to match the class.
If your injected field name does not match the bean name and there are more than one instance of your bean, Spring will throw an exception on startup as it won't know which one to inject.
Lets not over-complicate Spring.
#Bean
mqConnectionFactory() {
ConnectionFactory connectionFactory = new MQXAConnectionFactory();
return connectionFactory;
}
#Bean
public ConnectionFactory pooledConnectionFactory(ConnectionFactory mqconnectionFactory) {
JmsPoolConnectionFactory connectionFactory = new JmsPoolConnectionFactory();
connectionFactory.setConnectionFactory(mqConnectionFactory);
return connectionFactory;
}
#Bean
public ConnectionFactory cachingConnectionFactory(ConnectionFactory mqConnectionFactory) {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setTargetConnectionFactory(mqConnectionFactory);
return connectionFactory;
}
#Bean
public JmsTemplate jmsTemplate(ConnectionFactory cachingConnectionFactory) {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(cachingConnectionFactory);
return jmsTemplate;
}
#Bean
public DefaultMessageListenerContainer messageListenerContainer(ConnectionFactory pooledConnectionFactory) {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
container.setConnectionFactory(pooledConnectionFactory);
...
return container;
}
this is a springBoot1.5.22 project.I have 3 java config Bean ,use #Configuration and #Bean annotation.
when i try to run project with debug mode。why myBean method of ConfigurationC execute ? ,the myBean method of ConfigurationA and ConfigurationB not execute。what is mechanism ?
packages of the classes
start class
#Configuration
public class ConfigurationA {
#Bean
public MyBean myBean(){
System.out.println("ConfigurationA myBean init");
return new MyBean();
}
}
#Configuration
public class ConfigurationB {
#Bean
public MyBean myBean(){
System.out.println("ConfigurationB myBean init");
return new MyBean();
}
}
#Configuration
public class ConfigurationC {
#Bean
public MyBean myBean(){
System.out.println("ConfigurationC myBean init");
return new MyBean();
}
}
Like #jackycflau said in the comment above, all your beans have the same name.
These three beans, all with the same name and type, are being loaded (but not yet initialized) sequentially into the application context (bean container). When a bean named "myBean" of type MyBean is returned from the application context, you get the one from ConfigurationC because it was the last one written into the container, which overwrote the previous two beans of the same name/type. It's apparently not being initialized until it's actually pulled from the container by client code, which is why it's the only one whose code actually runs.
please provide code snippets to analyse it more.
Bean id should be unique. I don't think you would be allowed to create beans with same beanid.
please try below code
#Configuration
public class ConfigurationA {
#Bean
public MyBean myBean(){
System.out.println("ConfigurationA myBean init");
return new MyBean();
}
}
#Configuration
public class ConfigurationB {
#Bean
public MyBean myBean1(){
System.out.println("ConfigurationB myBean init");
return new MyBean();
}
}
#Configuration
public class ConfigurationC {
#Bean
public MyBean myBean2(){
System.out.println("ConfigurationC myBean init");
return new MyBean();
}
}
You can try specifying names:
#Bean(name="bean1")
and then select the injected bean:
#Autowired
#Qualifier("bean1")
In Spring Boot 1.5.x the bean overriding is enabled by default.
This means, the bean definition tree is built first and then the last overriding bean is used (executed), all others are ignored (as they were overrided). In your case the last definition comes from ConfigurationC.
This mechanism prevents from ambitious bean definitions, where more than one definition is found, and Spring can't know which one to use - an error occurs (BeanDefinitionOverrideException).
Please note, this must be explicit enabled in Spring Boot 2.x.
I have a simple spring boot app with the following config:
#Configuration
public class MyConfig {
#Bean
#Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HashMap<String, BidAskPrice> beanyBoi() {
System.out.println("creating a new one");
return dataFetcher().getPairPricesBidAsk();
}
}
and i have a service
#Service
public class ProfitCalculatorService {
#Autowired
private HashMap<String, BidAskPrice> prices;
public HashMap<String, BidAskPrice> getPrices() {
return prices;
}
}
and i have a controller
#RestController
public class TestController {
#Autowired
ProfitCalculatorService profitCalculatorService;
#GetMapping("/getprices")
public HashMap<String, BidAskPrice> someprices() {
return profitCalculatorService.getPrices();
}
}
}
now when i hit the /getprices endpoint, i was seeing some odd behaviour. The following message is logged twice: "creating a new one".
Your beans have a prototype scope, it means that every time that you asked for this bean a new instance will be created.
Official explanation:
The non-singleton prototype scope of bean deployment results in the
creation of a new bean instance every time a request for that specific
bean is made. That is, the bean is injected into another bean or you
request it through a getBean() method call on the container. As a
rule, you should use the prototype scope for all stateful beans and
the singleton scope for stateless beans.
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes-prototype
Another thing is the proxyMode with TARGET_CLASS value. It means that the bean injected into the ProfitCalculatorService is not the BidAskPrice itself, but a proxy to the bean (created using CGLIB) and this proxy understands the scope and returns instances based on the requirements of the scope (in your case prototype).
So, my suggestion is: You don't need to create an explicitly bean of HashMap<String, BidAskPrice>. Since BidAskPrice is a bean, you can inject the HashMap<String, BidAskPrice> directly in your service, Spring will manage this list for you!
Spring question.
I have two questions related to spring.
If I declare bean like this:
#Service
public class Downloader {
#Bean
public String bean1() {
return "bean1";
}
}
Then if other classes will be autowiring "bean1" then method bean1 will be called several times? Or one instance of bean1 will be created and reused?
Second question. How to Autowire some other bean e.g. "bean2" which is String "externalBean" that can be used to construct bean1.
#Service
public class Downloader {
#Autowire
private String bean2;
#Bean
public String bean1() {
return "bean1" + this.bean2;
}
}
Currently I'm trying to Autowire this bean2 but it is null during bean1 call. Is there any mechanism that I can specify order of this. I don't know in what context looking for this kind of info in Spring docs.
Just simple #Bean annotation used sets the scope to standard singleton, so there will be only one created. According to the docs if you want to change you need to explicitly add another annotation:
#Scope changes the bean's scope from singleton to the specified scope
Then if other classes will be autowiring "bean1" then method bean1
will be called several times? Or one instance of bean1 will be created
and reused?
There will be only a single instance of bean1, as the implicit scope is Singleton (no #Scope annotation present).
Second question. How to Autowire some other bean e.g. "bean2" which is
String "externalBean" that can be used to construct bean1.
Being that it is a String, a #Qualifier might be required
#Bean
#Qualifier("bean2")
public String bean2() {
return "bean2";
}
Then
#Bean
public String bean1(#Qualifier("bean2") final String bean2) {
return "bean1" + bean2;
}
However, this works too.
Spring will be able to look at the name of the Bean and compare it to the parameter's one.
#Bean
public String bean2() {
return "bean2";
}
and
#Bean
public String bean1(final String bean2) {
return "bean1" + bean2;
}
The order is calculated automatically by Spring, based on a Bean dependencies.
I have several beans:
#Bean
public MyBean myBean1(){
return new MyBean(1);
}
#Bean
public MyBean myBean2(){
return new MyBean(2);
}
#Bean
public MyBean myBean3(){
return new MyBean(3);
}
I would like to combine them into one collection and pass as an argument.
Something like:
#Bean
public MyFinalBean myFinalBean(Collection<MyBean> myBeans){
return new MyFinalBean(myBeans);
}
Is there a possibility to combine beans with annotations only? I.e. without using a separate method with applicationContext.getBeansOfType(MyBean.class);?
Spring is able to autowire all beans implementing the same interface into one collection of that interface. The following code works correctly:
#Bean
public MyFinalBean myObject(List<MyBean> lst) {
return new MyFinalBean(lst);
}