(6) Spring from entry to soil-Bean assembly mechanism

Spring Bean assembly mechanism

There are three assembly mechanisms for beans in Spring, namely:

  1. Explicit configuration in xml;
  2. Implicit bean discovery mechanism and automatic assembly.
  3. Explicit configuration in java; (java Config)

Spring's automatic assembly needs to be implemented from two perspectives, or two operations:

  1. Component scanning: Spring will automatically discover beans created in the application context;
  2. Autowiring: Spring automatically meets the dependencies between beans, which is what we call IoC/DI;

The combination of component scanning and automatic assembly exerts great power, which reduces the display configuration to a minimum.

Next, let’s take a look at how to use XML to display assembly and how to implicitly discover the mechanism of bean and automatic assembly.

Explicit configuration in XML

1. Create a new project

2. Create two new entity classes, Cat Dog has a method called

public class Cat {
   public void shout() {
       System.out.println("miao~");
  }
}
public class Dog {
   public void shout() {
       System.out.println("wang~");
  }
}

3. Create a new user class User

public class User {
   private Cat cat;
   private Dog dog;
   private String str;
}

4. Write Spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="dog" class="com.zhonghu.pojo.Dog"/>
   <bean id="cat" class="com.zhonghu.pojo.Cat"/>

   <bean id="user" class="com.zhonghu.pojo.User">
       <property name="cat" ref="cat"/>
       <property name="dog" ref="dog"/>
       <property name="str" value="zhonghu"/>
   </bean>
</beans>

5. Test

public class MyTest {
   @Test
   public void testMethodAutowire() {
       ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
       User user = (User) context.getBean("user");
       user.getCat().shout();
       user.getDog().shout();
  }
}

The result is normal output, the environment is OK

Automatic assembly

Automatic assembly instructions

  • Auto-wiring is a way to use spring to satisfy bean dependencies
  • Spring will automatically find in the context and automatically assemble properties for the bean.

It is recommended not to use automatic assembly xml configuration, but to use annotations.

byName automatic assembly

autowire byName (autowire by name)

In the process of manually configuring xml, errors such as missing letters and capitalization often occur, and cannot be checked, which reduces the development efficiency.

The use of automatic assembly will avoid these errors and simplify the configuration.

test:

1. Modify the bean configuration and add an attribute autowire="byName"

<bean id="user" class="com.zhonghu.pojo.User" autowire="byName">
   <property name="str" value="zhonghu"/>
</bean>

2. Test again, the result is still output successfully!

3. We modify the bean id of cat to catXXX

4. Test again and report a null pointer java.lang.NullPointerException during execution. Because the set method is not found according to the byName rule, the real setCat is not executed and the object is not initialized, so a null pointer error will be reported when it is called.

summary:

When a bean node has the attribute of autowire byName.

  1. It will find all the set method names in its class, such as setCat, and get the string with the set removed and the first letter lowercase, that is, cat.
  2. Go to the spring container to find if there is an object with this string name id.
  3. If there is, take out the injection; if not, report a null pointer exception.

It is necessary to ensure that the id of all beans is unique, and the bean needs to be consistent with the value of the set method of the automatically injected property

byType automatic assembly

autowire byType (automatic assembly by type)

The use of autowire byType first needs to ensure that objects of the same type are unique in the spring container. If it is not unique, a non-unique exception will be reported.

NoUniqueBeanDefinitionException

test:

1. Modify the user's bean configuration: autowire="byType"

2. Test, normal output

3. Register a cat bean object!

<bean id="dog" class="com.zhonghu.pojo.Dog"/>
<bean id="cat" class="com.zhonghu.pojo.Cat"/>
<bean id="cat2" class="com.zhonghu.pojo.Cat"/>

<bean id="user" class="com.zhonghu.pojo.User" autowire="byType">
   <property name="str" value="zhonghu"/>
</bean>

4. Test, error: NoUniqueBeanDefinitionException

5. Delete cat2 and change the bean name of cat! test! Because it is assembled by type, no exception will be reported and the final result will not be affected. Even removing the id attribute does not affect the result.

This is automatic assembly according to type!

It is necessary to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of automatically injected properties

Automatic assembly using annotations

jdk1.5 began to support annotations, and spring2.5 began to fully support annotations.

Preparation: Use annotations to inject attributes.

1. Introduce the context file header in the spring configuration file

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

2. Turn on attribute annotation support!

<context:annotation-config/>
@Autowired
  • @Autowired is automatically transferred by type and does not support id matching.
  • Need to import the spring-aop package!
  • You can use it directly on the attribute, or you can use it on the set method
  • Using Autowired, we don't need to write the Set method, provided that your auto-wired property exists in the IOC (Spring) container.

test:

1. Remove the set method in the User class and use the @Autowired annotation

public class User {
   @Autowired
   private Cat cat;
   @Autowired
   private Dog dog;
   private String str;

   public Cat getCat() {
       return cat;
  }
   public Dog getDog() {
       return dog;
  }
   public String getStr() {
       return str;
  }
}

2. The content of the configuration file at this time

<context:annotation-config/>

<bean id="dog" class="com.zhonghu.pojo.Dog"/>
<bean id="cat" class="com.zhonghu.pojo.Cat"/>
<bean id="user" class="com.zhonghu.pojo.User"/>

3. Test and output the result successfully!

@Autowired(required=false) Description: false, the object can be null; true, the object must be stored in the object, not null.

//如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
private Cat cat;
@Qualifier
  • @Autowired is automatically assembled according to the type, and @Qualifier can be automatically assembled according to the byName method
  • @Qualifier cannot be used alone.

Test experiment steps:

1. Modify the content of the configuration file to ensure that the object exists for the type. And the name is not the default name of the class!

<bean id="dog1" class="com.zhonghu.pojo.Dog"/>
<bean id="dog2" class="com.zhonghu.pojo.Dog"/>
<bean id="cat1" class="com.zhonghu.pojo.Cat"/>
<bean id="cat2" class="com.zhonghu.pojo.Cat"/>

2. No Qualifier test is added, and an error is reported directly

3. Add Qualifier annotations to the attributes

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

Test, output successfully!

@Resource
  • If @Resource has the specified name attribute, first perform byName search and assembly according to this attribute;
  • Then proceed to the default byName method for assembly;
  • If none of the above is successful, it will be automatically assembled in the byType method.
  • If it is not successful, an exception will be reported.

Entity class:

public class User {
   //如果允许对象为null,设置required = false,默认为true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}

beans.xml

<bean id="dog" class="com.zhonghu.pojo.Dog"/>
<bean id="cat1" class="com.zhonghu.pojo.Cat"/>
<bean id="cat2" class="com.zhonghu.pojo.Cat"/>

<bean id="user" class="com.zhonghu.pojo.User"/>

Test: the result is OK

Configuration file 2: beans.xml, delete cat2

<bean id="dog" class="com.zhonghu.pojo.Dog"/>
<bean id="cat1" class="com.zhonghu.pojo.Cat"/>

Only keep annotations on the entity class

@Resource
private Cat cat;
@Resource
private Dog dog;

Result: OK

Conclusion: The byName search is performed first, and it fails; then the byType search is performed, and it succeeds.

summary

Similarities and differences between @Autowired and @Resource:

1. Both @Autowired and @Resource can be used to assemble beans. Can be written on the field, or written on the setter method.

2. @Autowired is assembled by type by default (belonging to the spring specification). By default, the dependent object must exist. If you want to allow a null value, you can set its required attribute to false, such as: @Autowired(required=false), if We want to use the name assembly can be combined with @Qualifier annotations to use

3. @Resource (belonging to J2EE return), which is assembled by name by default, and the name can be specified by the name attribute. If the name attribute is not specified, when the annotation is written on the field, the field name is taken by default to search by name, if the annotation is written on the setter method, the attribute name is taken by default for assembly. When no bean matching the name is found, the assembly is performed according to the type. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.

They have the same function and are injecting objects with annotations, but the execution order is different. @Autowired first byType, @Resource first byName.

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

image

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/112405760