Technology Sharing

Spring - Autowire Beans

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

· Autowiring is a way for Spring to satisfy bean dependencies.

· Spring will automatically find the bean in the context and automatically assemble the properties


There are three ways to assemble in Spring:

1. Display configuration in xml

2. Display configuration in Java

3. Implicit automatic assembly of beans [Important]


test

Remember to create Cat, Dog, People classes

  1. public class MyTest {
  2. @Test
  3. public void test1(){
  4. ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  5. People people = context.getBean("people", People.class);
  6. people.getDog().shout();
  7. people.getCat().shout();
  8. }
  9. }

ByName Autowiring

  1. <!--
  2. byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
  3. -->
  4. <bean id="people" class="com.yang.pojo.People" autowire="byName">
  5. <property name="name" value="辰阳"/>
  6. </bean>

ByType Autowiring

  1. <bean class="com.yang.pojo.Cat"/>
  2. <bean class="com.yang.pojo.Dog"/>
  3. <!--
  4. byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean(必须保证类型全局唯一,如有两个狗就会报错)(可以省略id)
  5. -->
  6. <bean id="people" class="com.yang.pojo.People" autowire="byType">
  7. <property name="name" value="辰阳"/>
  8. </bean>

summary:

·  When using byname, you need to ensure that all bean ids are unique, and the bean must be consistent with the value of the set method of the automatically injected attribute.

·  When using bytype, you need to ensure that all bean classes are unique and that the bean type is consistent with the type of the automatically injected property.