Spring study notes-02 Bean scope, automatic assembly, annotation development

1. Bean scope

When the Spring IOC container creates a Bean instance, you can specify the scope for the Bean, including singleton (singleton mode, default option, only one for the entire project), prototype (prototype mode), request (Http request), session (session), global-session (global session) [the latter three are only valid in web projects].

(1)Singleton

There is only one entity class corresponding to bean id in the entire Spring IOC container, which is generally applicable to Service and DAO.

    <bean id="dog" class="com.zt.entity.Dog" scope="singleton">
        <constructor-arg index="0" value="汪汪"/>
        <constructor-arg index="1" value="2"/>
    </bean>

The default is Singleton, and the scope can also be displayed and written.

It is worth noting that the singleton mode we are talking about refers to that the entity class obtained by using the same bean id is the same, but if two bean types are the same but the bean id is different, then they are still two different Entity class.

[Note]: In java, the reference type == compares the memory address of the object storage.

    <bean id="dog" class="com.zt.entity.Dog">
        <constructor-arg index="0" value="汪汪"/>
        <constructor-arg index="1" value="2"/>
    </bean>
    
    <bean id="dog2" class="com.zt.entity.Dog">
        <constructor-arg index="0" value="汪汪"/>
        <constructor-arg index="1" value="2"/>
    </bean>

(2)Prototype

In the prototype mode, the beans obtained by using the IOC container are not the same each time, even if their bean id is the same.

    <bean id="dog" class="com.zt.entity.Dog" scope="prototype">
        <constructor-arg index="0" value="汪汪"/>
        <constructor-arg index="1" value="2"/>
    </bean>

(3)Request

In an Http request, a bean id corresponds to only one instance; it can be understood that in each request, the bean is a singleton mode (limited to the same bean id).

(4)Session

In a session, a bean id corresponds to only one instance.

(5)global session

Global Session (I don't understand it temporarily, I will add it after understanding).

2. Automatic assembly

Spring provides automatic assembly function, only simple configuration, we don't even need to configure ourselves for injection.

Autowire keyword: Used to specify the rules of Spring container to help us inject.

byName: When the id of a bean is the same as an attribute name of an entity class waiting to be injected, it can be injected

byType: When the type of a bean is the same as the type of an attribute of an entity class waiting to be injected, it can be injected

If the Beans registered in the container have the same type (or they all conform to the category of the properties injected by the generation, including the child and parent classes, interfaces), then using byType will report an error.

Of course, we can manually inject this attribute, and after Spring detects that the attribute is injected, it will not automatically inject it for us.

3. Annotation development

The configuration file has an obvious defect: a large number of rules must be written in the configuration file. When the integration of the system becomes high, the confusion of a large number of configuration files will cause confusion in the project, so we use annotations to replace configuration files in many places. , Which can greatly simplify the configuration file or even remove the configuration file. But this does not mean that the writing of the configuration file is outdated, because the configuration file has flexibility that cannot be achieved by annotations. Previously, in Mybatis, we had <sql> with <include> to extract repeated SQL, and we could also customize personalized resultMap. These It is impossible for annotations. The current common practice is to write in the configuration file where flexibility is necessary, and use annotations as much as possible to replace the others.

For the annotation to take effect, it is different from the configuration file. The configuration file can directly specify how to configure and where there is configuration; but the annotation must be realized after scanning to know. do you remember? In Mybatis, when we use annotation development, we need to change the registration of mapper to class and point to DAO.

1. The use of automatic assembly annotations

1. In order to use annotations, we must introduce context and modify the configuration file as follows:

<?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>

2. Configure the scanner

<context:component-scan base-package="com.zt"/>

3. Add Autowired annotations to the corresponding attributes of the classes that need to be assembled

    @Autowired
    private Stu stu;

4. Testing

There is a bean id with the same name as the property to be injected:

There is no bean id with the same name as the property to be injected, and there is a bean of the same type:

Of course, Spring also provides Qualifier annotations for use with Autowried, which can be injected by specifying the bean by bean id, which is also convenient for program inspection.

but! Java itself provides Resource annotations, and can also realize automatic assembly.

Explain the difference and connection in detail:

Contact: Both @Autowired and @Resouce can be used for automatic assembly, and both can be written on attribute fields or setters.

Difference: @Autowired is matched by type by default. By default, the object to be injected must exist, and it is not allowed to be null. You can also set its property required = false to allow assembly to be null. With @Qualifier annotation, you can use assembly by name.

@Resource according default name specified by the attribute name assembly name. If the name is not specified, if the annotation is on the field, the search is performed by name by default according to the field name; if the annotation is on the setter, it is searched according to the attribute name corresponding to the setter method. When the same name cannot be found, it will be assembled according to the type. However, if the name has been specified, it will only be assembled according to the name. That is, name -> byName -> byType.

2. Component annotation

After we introduce the annotations, we don't need to configure beans in the configuration file, but use component annotations to tell Spring which classes need to be managed by the Spring container as beans.

@Component: You can declare those classes that need to be managed by Spring as beans; @Component + value replaces <bean id = "" class = ""></bean>

You can use @Resource assembly.

You can also use @Autowired+@Qualifier assembly.

1) Use @Value for basic type injection.

2) Use @Autowired+@Qualifier to automatically assemble reference types.

3) Complex objects such as arrays, lists, and maps are not easy to directly use annotations for injection, which also highlights the flexibility of configuration files.

3. Layered development notes 

In fact, in project development, we will layer the project: Controllr-Service-DAO

@Repository: Used to mark the DAO layer.

@Service: Used to mark the Service layer.

@Controller: Used to mark the Controller layer.

Classes with the above annotations will also be managed as beans by the Spring container after being scanned by the scanner.

4. Configuration class (we can use Java configuration class instead of configuration file)

@Bean: Pass the existing objects in the container as parameters, and save the returned objects in the container for management.

@Configurable: Declares that the current class is a configuration class.

When we use annotations for configuration, we may need to refer to the classes in the jar package. At this time, we have no way to modify those classes directly. To obtain its objects and store them in the container, we can only use the above annotations. For example, cats eat mice and mice are used as food for cats. Now we cannot modify cats and mice, but we want to return a cat that has mice as food.

Mouse.java

package com.zt.config;

public class Mouse {
    private String name;

    public Mouse() {
    }

    public Mouse(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Mouse{" +
                "name='" + name + '\'' +
                '}';
    }
}

Cat.java

package com.zt.config;

public class Cat {
    private String name;
    private Mouse mouse;

    public Cat() {
    }

    public Cat(String name, Mouse mouse) {
        this.name = name;
        this.mouse = mouse;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Mouse getMouse() {
        return mouse;
    }

    public void setMouse(Mouse mouse) {
        this.mouse = mouse;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", mouse=" + mouse +
                '}';
    }
}

TestConfig.java

package com.zt.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {

    @Bean
    public Mouse mouse(){
        return new Mouse("jerry");
    }

    @Bean
    public Cat cat(Mouse mouse){
        return new Cat("Tom",mouse);
    }
}

test:

import com.zt.config.Cat;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.zt.config.TestConfig;
public class TestClassConfig {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        Cat cat = context.getBean(Cat.class);
        System.out.println(cat);
    }
}

Talk about annotations and xml configuration files: Many years ago, the industry generally believed that the use of configuration files can complete the decoupling of the program, and since our project is ultimately packaged into a class+ configuration file, it is very important to directly modify the source code Unrealistic things, so you can modify the project by modifying the configuration file (such as replacing the connection pool, etc.); but the configuration file method will cause the entire project to be overwhelmed by a large number of configuration files, so the current mainstream is to configure Documented, that is, for some almost fixed usage annotations, for some that may change frequently or are more flexible, the configuration file is still used, which simplifies the configuration file.

 

Guess you like

Origin blog.csdn.net/qq_39304630/article/details/112368667