Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Create bean in XML with reference to Java bean, and the other way around

Tags:

java

spring

If I have a bean created in Java, with @Bean, how do I reference this bean in XML when creating a bean there? And if I have a bean created in XML, how do I reference this bean in Java when creating a bean there?

like image 483
Kims Avatar asked Sep 09 '19 05:09

Kims


1 Answers

Other answers only answer part of the picture. Let me try to summarize the big picture. The key point is that every bean has an identifier which is unique within the spring container. We can use this identifier to reference a bean.

The bean identifier can be configured by :

  • XML : id and name attribute in the <bean/>
  • Java Config :
    • value and name attribute in @Bean .
    • value attribute in@Component and its stereotype annotation such as @Service , @Controller etc.

If the identifier is not configured explicitly , depending on how the beans are declared , a default one will be generated for them:

  • For beans declared using XML, @Component and its stereotype , it is the class name of that bean formatted in lowerCamelCase.

  • For beans declared using @Bean , it is the name of that bean method

To reference a bean declared in Java configuration in XML , use ref property to refer to its identifier such as :

   <bean name="foo" class="com.example.Foo">
        <property name="service" ref="bar"/>
    </bean>

So service property is reference to a bean which the identifier is called bar

To reference a bean declared in XML in Java , you can simply annotate @Autowired on a field. If there is only one spring bean which the type is the same as the type of this field (i.e. Bar in this case) , this bean will automatically be referenced and injected . It is called auto-wired by type which you does not require to reference it by the bean identifier :

@Service
public class Foo {

   @Autowired   
   private Bar service;

}

On the other hand , if there are multiple beans which the type are also Bar, you have to use @Qualifier with the bean identifier to reference a particular bean among these Bar beans. This is called auto-wired by name :

@Service
public class Foo {

   @Autowired   
   @Qualifier("bar123")
   private Bar service;

}
like image 143
Ken Chan Avatar answered Sep 30 '22 19:09

Ken Chan