Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

=

When the Spring container initializes an instance of a Bean, it also specifies the scope of that instance.

Scope Description
Singleton (commonly used) In the singleton pattern, beans defined using singleton have only one instance in the Spring container, which is also the Bean’s default scope.
prototype In prototype mode, each time a prototype-defined Bean is fetched from the Spring container, the container creates a new instance of the Bean.
request In an HTTP request, the container returns the same instance of the Bean. For different HTTP requests, different instances are returned. This scope is valid only within the current HTTP Request.
session In an HTTP Session, the container returns the same instance of the Bean. For different HTTP requests, different instances are returned. This scope is valid only for the current HTTP Session.
application Limit the scope of the individual bean definition toServletContextLife cycle of. Only in network-aware SpringApplicationContextValid in context.
websocket Limit the scope of the individual bean definition toWebSocketLife cycle of. Only in network-aware SpringApplicationContextValid in context.

1. Bean scope

1. Singleton scope

Singleton is the default scope of the Spring container. When the scope of a Bean is Singleton, there will be only one shared Bean instance in the Spring container, and all requests to the Bean, as long as the ID matches the Bean definition, Only the same instance of the Bean is returned.

In the Spring configuration file, the scope display of the bean can be defined as a Singleton using the scope attribute of the

element as follows:

<bean id="user" class="com.cheng.pojo.User" scope="singleton"/>
Copy the code
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
        User user1 = context.getBean("user", User.class);
        System.out.println(user==user1);//true
Copy the code

The result is true, indicating that the Spring container created only one instance of the User class. Since the Spring container’s default scope is Singleton, if scope=” Singleton “is not set, the output will also be an instance.

Prototype scope

A Bean that uses the Prototype scope creates a new instance of the Bean each time it is requested. Therefore, use the Prototype scope for beans that need to maintain session state.

To define a Bean as a Prototype scope in the Spring configuration file, simply define the element’s scope attribute value as prototype, which looks like this:

<bean id="user2" class="com.cheng.pojo.User" c:name="Thousands of miles" c:age="3" c:address-ref="address" scope="prototype"/>

Copy the code
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user2", User.class);
User user1 = context.getBean("user2", User.class);
System.out.println(user==user1);//false
Copy the code

The two outputs are different, indicating that the Spring container created two different Instances of Person under the Prototype scope.

2. Automatic assembly of beans

What is autowiring:

  • Autowiring is one way Spring satisfies bean dependencies
  • The Spring container can autowire associations between cooperating beans, injecting one Bean into another Bean’s Property.

To use autowire, you need to configure the Autowire attribute of the

element. The autowire attribute has five values, as described in the following table.

The name of the instructions
byName If the name of one Bean is the same as the name of the Property in another Bean, the Bean is automatically assembled into the Property.
byType Automatic assembly is based on the data Type of the Property, if the data Type of one Bean is compatible with the data Type of the Property in another Bean.
constructor ByType schema is automatically assembled based on the data types of constructor parameters.
autodetect Use the constructor pattern if a default constructor is found, otherwise use the byType pattern.
no By default, instead of using autowiring, Bean dependencies must be defined through the REF element.

Environment set up

package com.cheng.pojo;

public class Person {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat(a){
        return cat;
    }
    public void setCat(Cat cat){
        this.cat=cat;
    }
    public Dog getDog(a){
        return dog;
    }
    public void setDog(Dog dog){
        this.dog=dog;
    }
    public String getName(a){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }

    @Override
    public String toString(a) {
        return "Person{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\' ' +
                '} '; }}Copy the code
package com.cheng.pojo;

public class Dog {
    public void shout(a){
        System.out.println("wang~"); }}Copy the code
package com.cheng.pojo;

public class Cat {
    public void shout(a){
        System.out.println("miao~"); }}Copy the code

ByName automatic assembly

ByName: The

ID that corresponds to the value after the set method of your own object is automatically looked up in the container context. The

ID must be globally unique

<bean id="cat" class="com.cheng.pojo.Cat"/>
<bean id="dog" class="com.cheng.pojo.Dog"/>    
<bean id="person" class="com.cheng.pojo.Person" autowire="byName">
    <property name="name" value="Thousands of miles"/>
</bean>
Copy the code

ByType automatic assembly

ByType: the

type is automatically looked up in the container context. The

type must be globally unique

<bean id="cat" class="com.cheng.pojo.Cat"/>
<bean id="dog111" class="com.cheng.pojo.Dog"/>    
<bean id="person" class="com.cheng.pojo.Person" autowire="byName">
    <property name="name" value="Thousands of miles"/>
</bean>
Copy the code

3. Use annotations for autowiring

Java has provided Annotation functionality since JDK 5.0, and Spring has provided full support for Annotation technology since 2.5.

Use the annotations to import the configuration file:


      
<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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <! -- Enable annotation support -->
    <context:annotation-config/>

</beans>
Copy the code

Common comments are as follows.

1) @ Component

You can use this annotation to describe beans in Spring, but it is a generalized concept that represents only a component (Bean) and can be applied at any level. To use it, simply annotate the annotation on the corresponding class.

2) @ the Repository

Classes used to identify the data access layer (DAO layer) as beans in Spring have the same functionality as @Component.

3) @ Service

Typically at the Service layer, it identifies the business layer’s classes as beans in Spring, with the same functionality as @Component.

4) @ Controller

Typically applied to the control layer to identify the control layer’s classes as beans in Spring, with the same functionality as @Component.

5) the @autowired

It is used to annotate the Bean attribute variables, attribute Set methods and constructors, and complete the automatic configuration of the Bean with the corresponding annotation processor. The default assembly is based on the type of Bean. If @autowired is used on a property, you can ignore its set method.

@Autowired
private Cat cat;
@Autowired
public void setDog(Dog dog){
     this.dog=dog;
    }
Copy the code

Supplement:

  • The @nullable field marks the annotation, indicating that the field can be null.

    public void setName(@Nullable String name){  // The name attribute can be null
        this.name=name;
        }
    Copy the code
  • // If the display defines @autoWired (required = false), then the current bean object can be null
    @Autowired(required = false)
    Copy the code

6) @ the Qualifier

When used with the @AutoWired annotation, the default assembly by Bean type is changed to assembly by the instance name of the Bean, which is specified by the @Qualifier annotation parameter when a Bean of a type has multiple instance names.

<bean id="cat1" class="com.cheng.pojo.Cat"/>
<bean id="cat2" class="com.cheng.pojo.Cat"/>
<bean id="cat3" class="com.cheng.pojo.Cat"/>
Copy the code

@ the use of the Qualifier

@Autowired
@Qualifier(value="cat2")
private Cat cat;
Copy the code

7) @ the Resource

It does the same as Autowired. The difference is that @AutoWired is assembled by default by Bean type, while @Resource is assembled by default by Bean instance name.

There are two important attributes in @resource: name and type.

Spring resolves the name attribute to the Bean instance name and the Type attribute to the Bean instance type. If the name attribute is specified, assembly is performed by instance name; If the type attribute is specified, assembly is performed by Bean type.

If neither is specified, the Bean instance name is used for assembly. If no match is found, the Bean type is used for assembly. If can’t match, the thrown NoSuchBeanDefinitionException anomalies.