Spring IOC annotation configuration

Spring IOC annotation configuration

(1) Brief description

As mentioned last time, we can use the way of writing XML configuration files to let Spring generate the Bean objects we need and put them into the container. However, writing configuration files is a very cumbersome task, and once the configuration file contains a lot of content, it is also a headache to read. Therefore, we urgently need a configuration method that partially or completely gets rid of configuration files.

Let's take a look at Spring's annotation configuration method. Annotation configuration is compared with configuration file configuration, only the form of configuration is different, and the ultimate goal is basically the same. It's like going to Beijing by plane and going to Beijing by high-speed rail. Although the means of transportation are different, they both achieve the goal of going to Beijing.

(Two) annotation classification

The annotations used for configuration can be roughly classified like this: those used to create objects, those used to inject data, those used to change the scope, and those used to add logic to the life cycle. These annotations will replace some of the configuration content in the XML file, but cannot completely get rid of the XML file (how to get rid of the XML file completely later).

First of all, we have to introduce the context namespace in XML:

Insert picture description here

Directly give a template on the official document:

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

</beans>

Then, we need to add a scanner so that spring can find classes with annotations for creating objects before they can be instantiated and included in the spring IOC container:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
        
	<context:component-scan base-package="com.demo" />
</beans>

The base-package here refers to the package where all beans that need to be added to the container are located. With the scanner, let's take a look at how to use these four types of annotations.

1. Used to create objects

There are a total of four such annotations, namely: @Component, @Controller, @Service, and @Repository. Their role is equivalent to writing the <bean /> tag in the XML configuration file.

First, let's look at the @Component annotation. Its function is to store the current object in the spring IOC container. @Component is a generic name, which generally refers to any component that can be managed by Spring. @Controller, @Service, @Repository are extensions of @Component, which are usually used to represent components in a specific situation, and the Spring framework will Do some customization according to this application scenario, for example, @Repository also has automatic exception conversion. @Repository is used to represent Dao layer components, @Service is used to represent Service layer components, and @Controller is used to represent Controller layer components.

Therefore, when special customization is not considered, these four annotations are exactly the same and can be mixed. But generally we still choose according to the nature of the component. Let's just write a look:

package com.demo;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
    
    
    public void getUser(){
    
    
        System.out.println("getUser被调用了");
    }
}

These four annotations have a parameter to specify the name of the Bean object. If you don't write it (I didn't write it here), the default is the class name and the first letter is changed to lowercase. This annotation is equivalent to what we configured in XML:

<bean id="userDao" class="com.demo.UserDao" />

2. Used to inject data

With objects, we may also inject data. Commonly used annotations of this type are: @Value, @Autowired, @Resource. The functions of these three annotations are equivalent to the <property /> tag in the <bean /> tag, @Value is responsible for Basic types are injected, while the other two are responsible for injecting object types (dependency injection).

@Value has nothing to say, just write the value to be injected in the annotation attribute, the other two may be a bit complicated.

@Autowired defaults to inject according to the type matching method, which can be used for member variables, setter methods, constructor functions, etc., using @Autowired annotations must have and only one Bean object matching the type, if there are multiple matching Beans At the time, it will match according to the name. If the matching object is not found, the Spring container will throw an exception (if you don't want to throw an exception, you can add attributes to the annotation: required=false). We can also specify the name of the injected Bean object through the @Qualifier annotation. When @Autowired and @Qualifier are used in combination, the automatic injection strategy changes from matching by type to matching by name.

Insert picture description here

Insert picture description here
After using the @Resource annotation, spring determines whether the name attribute of the annotation is empty. If it is empty, it will match the current attribute name with the name of the Bean object in the spring IOC container. If the match is successful, it will be assigned. If the match is unsuccessful, then It will match according to the class type of the spring configuration file. If the match is still unsuccessful, an error will be reported. If there is a name attribute, it will be matched according to the value of the name attribute and the name of the Bean object in the spring IOC container. If the match is successful, it will be assigned, and if it is not successful, an error will be reported.

Insert picture description here

3. Used to change the scope of action

There is only one annotation of this type, namely @Scope, which is equivalent to the scope attribute in the <bean /> tag.

@Scope is used to change the scope of the Bean object. The attributes can be filled with the following values, which are the same as in the XML configuration:

  1. singleton: singleton mode
  2. prototype: multiple cases mode
  3. request: request domain, need to be in the web environment
  4. session: session domain, need to be in the web environment
  5. application: context domain, need to be in the web environment
  6. The session domain of the globalsession cluster environment needs to be in the web environment

4. Used to add logic to the life cycle

There are two main types of annotations, @PostConstruct and @PreDestroy, which are used on methods, which are equivalent to the init-method and destroy-method attributes in the <bean /> tag.

    @PostConstruct
    public void init() {
    
    
    	System.out.println("初始化方法......");
    }
    
    @PreDestroy
    public void destroy() {
    
    
    	System.out.println("销毁方法......");
    }

After reading so many annotations, let's summarize. In fact, each annotation here corresponds to a configuration function in the previous XML, so it is easy to correspond to memory.

Types of annotation Corresponding XML element
Used to create objects @Component、@Controller、@Service、@Repository <bean /> tag
Used to inject data @Value、@Autowired、@Resource The <property /> tag in the <bean /> tag
Used to change the scope of action @Scope The scope attribute in the <bean /> tag
Used to add logic in the life cycle @PostConstruct、@PreDestroy The init-method attribute and destroy-method attribute in the <bean /> tag

(3) Pure annotation configuration

Pure annotation configuration allows us to finally abandon the XML file, but we need to write a configuration class to replace his function.

Let's think about what might be in this configuration class. First, how does spring know that it is a configuration class? We have to add a special annotation for the configuration class. This annotation is @Configuration. With him, this class will be treated as a configuration class.

Then, we also talked about that we have previously configured a scanner in XML, this has also become an annotation in the configuration class, he is @ComponentScan, we only need to fill in the package we need spring scanning. Note that if you want to fill in multiple packages here, we need to write them in array form. Let's look at an example:

package com.demo;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.demo")
public class Config {
    
    

}
package com.demo;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
    
    
    public void getUser(){
    
    
        System.out.println("getUser被调用了");
    }
}

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    
    @Autowired
    private UserDao userDao;

    public void get(){
    
    
        userDao.getUser();
}

This example is very concise, and the main purpose is to show the pure annotation configuration mode. Obviously, none of the things we previously configured in XML were missing. This also confirms what I said before: XML configuration and annotation configuration, but the form is different, the final goal is basically the same. what? Can you save the configuration class? Is there someone lazier than me? Of course, it is possible, but you need to go out and turn right to take a look at springboot, to appreciate that the convention is greater than the configuration, and to experience how smart an application can be run without writing a line of code.

However, it is not recommended for beginners to go to see springboot directly. The reason is very simple. If you don't understand the principle of spring, you will doubt your life when debugging. We learn spring, in addition to learning how to use the framework, more is to learn what is a top Java project, what is called a specification, and what is a design pattern. Only when you can understand these can you really learn spring at home. By then, it is not impossible to write a spring framework by yourself.

May 13, 2020

Guess you like

Origin blog.csdn.net/weixin_43907422/article/details/106068251