Explain in detail the principle and use of @ Autowired for annotation injection of Spring bean

  • 2021-09-20 20:17:30
  • OfStack

1. @Autowired

Concepts:

@ Autowired annotation, which can annotate class member variables, methods and constructors to complete automatic assembly. Eliminate set and get methods by using @ Autowired.

Before using @ Autowired, when we configured properties for an bean, we used


<property name=" Attribute name " value="  Attribute value "/>    

After using @ Autowired, we only need to use one @ Autowired where we need to use it.

Code usage:


public interface StudentService {
    public boolean login(String username,String password);
}

@Service
public class StudentServiceImpl implements StudentService {

    @Override
    public boolean login(String username,String password) {
       if("crush".equals(username)&&"123456".equals(password)){
            System.out.println(" Login Successful ");
            return true;
        }
        return false;
    }
}

@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;
        public void login(){
       boolean crush = studentService.login("crush", "123456");
       if(crush){
           System.out.println("crush"+" Login successful! ! ! ! ! ");
       }else{
           System.out.println(" Login failed ");
       }
    }
}

Test:


@Test
    public void login(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        StudentController student = applicationContext.getBean("studentController", StudentController.class);
        student.login();
    }

We don't have to go to the xml file to continue configuration after using @ Autowired.

Pay attention to details:

1. The current class using @ Autowired must also be hosted by the spring container (call @ Coponent, @ Controller, @ Service, @ repository)

2. Both public and private modified fields can be automatically injected

3. By default, attribute 1 with @ Autowired annotation must be assembled. If this type of bean injection cannot be found in the container, an error will be reported. If allowed not to be assembled, the required attribute of @ Autowired can be changed to false

4. @ Autowired is type-based injection. If the current type attribute has only one Bean in the container, the attribute name is not limited, but it is generally recommended to follow the rule that the first letter of the class name is lowercase.

5. If the current attribute type has more than one Bean in the container, Bean name must be specified by the attribute name or @ Qualifier

6. @ Autowired can be typed on XXX [] and List. At this time, all bean of XXX type in the container will be injected, and the attribute name is not constrained. However, note that bean of beanName can be injected through @ Qualifier, and the attribute name has no constraint effect

7. @ Autowired can be played in Map < String,XXX > At this time, all bean of XXX type will be injected, beanName is key, and the object is value, but note that bean of beanName can be injected through @ Qualifier, and the attribute name has no constraint effect

2. @ Service, @ Repository, @ Controller, @ Component

These annotations all have the same meaning, are written on the class or interface, and will be automatically registered with the Spring container.

1. @ Service is used to annotate business layer components
2. @ Controller is used to annotate control layer components (such as action in struts)
3. @ Repository is used to annotate data access components, that is, DAO components.
4. @ Component generally refers to components. When components are not easy to classify, we can use this annotation to annotate them. Register in the Spring container.

Use


@Service
public class StudentServiceImpl implements StudentService {
}

@Controller
public class StudentController {
}

This is the equivalent of writing the following code in the application. xml file


<bean id="studentServiceImpl" class="com.crush.service.impl.StudentServiceImpl"/>
<bean id="studentController" class="com.crush.controller.StudentController"/>

Of course, if you want the annotation to take effect, it is necessary to add such a 1-line scan package code


<!-- Jean com.crush Use in the class under the package  spring The annotation of takes effect -->
<context:component-scan base-package="com.crush"/>

3. @Bean

@ Bean clearly indicates a method, what method-the method of generating an bean and handing it over to the Spring container for management; From this we can see why @ Bean is placed on the annotation of the method, because it clearly tells the annotated method that you generate an Bean for me, and then give it to the Spring container, and you leave the rest alone

4. @Configuration

@ Configuration is used to define configuration classes.

At present, Spring has two configuration modes, one is xml file configuration plus Java code, which has existed since Spring was born, and the other is completely configured and written by Java code, which is released in the later version of Spring.

From Spring3.0, @ Configuration is used to define configuration classes, and the annotated classes that can replace xml configuration files contain one or more methods annotated by @ Bean, which will be scanned by AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext classes, and used to build bean definitions and initialize Spring containers.

This method is more popular with java programmers.


@Configuration
public class MyConfig {
}

And this way in the follow-up study, in the Spring source code is used very much.

5. @Resource

The function of @ Resource is equivalent to @ Autowired, except that @ Autowired presses byType for automatic injection, while @ Resource presses byName for automatic injection by default. Two important attributes of @ Resource are name and type. Spring resolves the name attribute of @ Resource annotation to the name of bean, while type attribute resolves to the type of bean. So if the name attribute is used, the byName auto-injection policy is used, while the byType auto-injection policy is used when the type attribute is used. If neither the name nor the type attribute is specified, the byName auto-injection policy is used through reflection.

The difference between @ Autowired and @ Resource

Principle of @ Autowired


Related articles: