Xml-based use

The IoC to configure

The IoC is configured through a bean tag in the Spring XML file.

Bean Label Introduction

  • The Bean tag is used to configure information about beans managed by the Spring container. By default it calls the no-argument constructor in the class, and it cannot be created without a no-argument constructor.

  • Bean Tag Attribute

    • Id: Provides a unique identifier for the object in the container and is used to obtain the object.

    • Class: Specifies the fully qualified name of the class used for reflection to create the object. By default, the no-argument constructor is called.

    • Init-method: Specifies the name of the founding method in the class.

    • Destroy-method: Specifies the name of the destroy-method in the class. For example, in a DataSource configuration, you need to specify destroy-method=”close”

    • Scope: Specifies the scope of the object.

      • Singleton: The default, singleton (only one object in the entire container), has the following life cycle:

        • Object birth: The object is created when the application loads and the container is created.
        • Objects live: Objects live as long as the container exists.
        • Object death: When the application is uninstalled and the container is destroyed, the object is destroyed.
      • Prototype: The object instance is recreated every time the object is accessed. The lifecycle is as follows:

        • Object Birth: When an object is used, a new object instance is created.
        • Object alive: As long as the object is in use, it is alive.
        • Object death: When an object has not been used for a long time, it is collected by Java’s garbage collector.
      • Request: Saves Bean objects created by Spring into the request domain.

      • Session: Stores spring Bean objects in the Session domain.

      • Global Session: In WEB projects, a Global session is used in a Protlet environment. If there is no Protlet environment, then a Global session is a session.

Three ways to instantiate beans

  • Use the default no-argument constructor (important)

    By default: it creates objects according to the default no-argument constructor. If the bean does not have a default no-argument constructor, the creation will fail.

    <bean id="id" class="com.XXX.XXX"/>

  • Second: Static factory (understand)

    Use the static method CreateBean in class StaticFactory to create an object and store it in the Spring container:

    Public class static factory {public static Bean createBean (){return new Bean(); }}Copy the code

    <bean id="XXX" class="com.XXX.XXX.StaticFactoty" factory-method="createbean"></bean>

  • Type 3: Example factory (understand)

    Let Spring manage the creation of the factory first, and then use the beans of the factory to call the methods inside

    /** * Simulate an instance factory, create an object, Public class IntanceFactory{public static Bean createBean (){return new Bean(); }}Copy the code

    <bean id ="instancFactory" class="com.XXX.XXX.IntanceFactory"> </bean>

    <bean id ="XXX" factory-bean="instancFactory" factory-method="createbean"> </bean>

DI configuration

Rely on

  • Dependencies refer to properties in Bean instances
  • Dependencies (properties) are divided into: properties of simple types (the eight basic types and String types), properties of POJO types, and properties of collection array types.

Dependency injection

  • Dependency Injection It is a concrete implementation of the Core IoC of the Spring framework.

Do dependency injection

  • Our program was written to hand over object creation to Spring through inversion of control, but it is impossible to have no dependencies in the code.
  • If a bean contains several properties, spring will assign the corresponding properties to the bean object after it is instantiated. This is called dependency injection (get the value, inject the property).

The way of dependency injection

  1. Constructor injection
Assign values to member variables using class constructors. Note that the assignment is not done by us, but is configured to be injected by the Spring framework.Copy the code
public class User{ private int id; private String name; public User(int id,String name){ this.id = id; this.name = name; }}Copy the code
<bean id="user" class="com.XXX.XXX.User"> <constructor-arg name="id" value="1"></constructor-arg> <constructor-arg </constructor-arg> </bean>Copy the code

Using construction, passing values to an object’s properties requires that the class provide a constructor for the corresponding argument list

Labels involved:

  • constructor-arg

    • Index: Specifies the index position of the argument in the constructor list
    • Name: Specifies the name of the argument in the constructor
    • Value: It can assign values of basic data types and String types
    • Ref: It can assign values to other bean types, that is, it must be the bean that has been configured in the configuration file
  1. Set method injection (emphasis)

    • Manual assembly (XML)

      • The subtag property of the bean tag needs to be configured
      • Specify setter methods in the beans that need to be configured
    • Automatic assembly (annotated)

      • @Autowired

        • Function 1: Find an instance from the Spring container based on the Bean type (byType)
        • Function two: assign, will find the instance, assembly to another instance attribute value
        • Note: There can be only one instance of a Java type in the same Spring container
      • @Resource

        • Function 1: Look for an instance from the Spring container based on the Bean name (byName)
        • Function two: assign, will find the instance, assembly to another instance attribute value
      • @Inject

  2. The data is injected using the P name

    • You’re essentially calling the set method

      • Step 1: You need to introduce the P namespace first

      The schema namespace to join the bank: XMLNS: p = "http://www.springframework.org/schema/p"

      • Step two: Use the syntax of the P namespace
      P: attribute name = "" P: attribute name -ref = ""Copy the code

Dependency injection for different types of properties

  • Simple type (value)
<bean id="user" class="com.XXX.XXX.User"> <constructor-arg name="id" value="1"></constructor-arg> <constructor-arg </constructor-arg> </bean>Copy the code
  • Reference type (ref)
<bean id="user" class="com.XXX.XXX.User">
       <property name ="car" ref="car"></property>
</bean>
<bean id="car" class="com.XXX.XXX.Car"></bean>
Copy the code
  • Collection type (array)

    • If it is an array or a list collection, the configuration file is injected in the same way
    <bean id="user" class="com.XXX.XXX.User"> <property name="arrs"> <list> <! Use the value subtag if the collection is a simple type, or if it is a POJO type. </property> </property> </property> </property> </property> </property>Copy the code
    • In the case of a Set, the configuration file is injected as follows:
    <bean id="user" class="com.XXX.XXX.User"> <property name="sets"> <set> <! Use the value subtag if the collection is a simple type, or if it is a POJO type. </set> </property> </property> </property> </property>Copy the code
    • For a Map set, the injection configuration is as follows
    <bean id="user" class="com.XXX.XXX.User"> <property name="map"> <map> <! If the collection is a simple type, use value, if it is a POJO type, Use the ref - > < entry key = "key1" value = "23" / > < entry key = "key2" ref = "" > < / map > < / property > < / bean >Copy the code
    • In the case of a Properties collection, the injection configuration is as follows:
    </prop> </prop> </prop> </prop> </prop> </prop> </prop> </bean>Copy the code

Based on the use of annotations and a mixture of XML

Use of IoC annotations

  • Step 1: In the Spring configuration file, configure the Context: Component-scan tag

  • Step 2: Annotate the class @Component, or its derivative @controller, @Service, or @repository

Commonly used annotations

The IoC annotations

  • The Component annotation

    • What it does: Having resources managed by Spring is equivalent to configuring a bean in XML.
    • Property: value: specifies the bean ID. If the value property is not specified, the default bean ID is the class name of the current class, starting with a lowercase letter.
  • @Controller, @Service, @repository annotations

    All three annotations are derivative annotations for @Component, and their functions and properties are identical. They simply provide more explicit semantics.

    Note: If there is only one attribute in the annotation to assign a value, and the name is value, value may not be written when assigning

    • @controller: Generally used for presentation layer annotations
    • @service: Generally used for business layer annotations
    • @repository: Typically used for persistent layer annotations

DI annotations (dependency Injection)

  • @Autowired

    • @autowired defaults to assembly byType (byType)
    • The @autowired consists of AutowiredAnnotationBeanPostProcessor class implements
    • The @autowired annotation comes with Spring
    • @autowired requires dependent objects to exist by default. If you want to allow null values, you can set its required attribute to false, such as: @autowired (Required =false)
    • If we want to assemble byName (byName) we can use it in conjunction with the @qualifier annotation
  • @Qualifier

    • In addition to the automatic injection by type, it is injected by Bean ID
    • It cannot be used in isolation for field injection and must be used in conjunction with @autowire
    • However, when injecting method parameters, they can be used independently
  • @Resource

    • @resource is assembled byName (byName) by default. You can specify the name through the name attribute of @resource. If the name attribute is not specified, when the annotation is written on the field, the name of the field is chosen by default and the bean is assembled by type only when no bean matching the name is found
    • @Resource is an implementation of the J2EE JSR250 specification
    • Note, however, that if the name attribute is specified, it will only be assembled by name

The @resource annotation is recommended because it belongs to J2EE and reduces the coupling with Spring.

  • @Inject

    • @Inject is automatically assembled according to type. If you need to assemble by Name, you need to cooperate with @Name
    • Inject @inject is a specification in JSR303 that needs to import javax.inject.Inject to implement injection
    • Inject @inject can be applied to variables, setter methods, and constructors
  • @Value

    • Inject values to the basic and String types
    • You can use placeholders to get values in a properties file
  • @autowired, @Resource, @inject

    • @Autowired is shipped with Spring, @Resource is implemented by the JSR250 specification, and @Inject is implemented by the JSR330 specification, requiring different packages to be imported
    • @autowired and @inject are basically the same, except that @autowired has a request attribute
    • @autowired and @Inject are matched by type by default, and @Resource by name
    • @autowired should be used with @Qualifier and @Inject with @name if you want to match by Name

Annotations that change the scope of the Bean

  • @scope: Specifies the Scope of the bean, equivalent to the following configuration:

    <bean id="" class="" scope=""></bean>

    • Property: value: Specifies a range of values. Values: Singleton Prototype Request Session GlobalSession

Lifecycle related annotations

  • @PortConstruct
  • @PreDestroy

About XML versus annotations

  • annotations

    Simple configuration and easy maintenance (we find the class, we find the corresponding configuration)

  • XML

    No changes to the source code are required, and recompilation and deployment are not involved

  • Comparison of how Spring manages beans

XML annotations
Bean definition @Component derived class @controller @Service @repository
The name of the Bean Specified by id or name @Component(“XXX”)
Bean injection Or the P namespace @AutoWired by type @Qualifier by name
Life process, Bean scope Init-method destroy-method Scope attribute @portConstruct initializes @preDestroy to destroy @scope Scope
Suitable for the scene Beans come from third parties, using other implementation classes The implementation classes for beans are developed by the users themselves

Use in a purely annotated manner

  • @Configuration

    • Equivalent to Spring’s XML configuration file

    • Starting with spring3.0, you can define Configuration classes using @configuration, which can replace XML Configuration files

    • Configuration class contains by one or more @ Bean annotation methods, these methods will be AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext scan, It is used to build bean definition objects and initialize the Spring container. Spring initialization calls the parameterless constructor of the configuration class.

    • Properties:

      • Value: The bytecode used to specify the configuration
  • @Bean

    • Equivalent to the bean tag

    • Register beans to configure non-custom beans, such as DruidDataSource and SqlSessionFactory

    • @bean annotation on method (returns method of an instance)

    • Properties:

      • Name: specifies a name (that is, the Bean ID) for the object created by the current @bean annotation method. If not specified, the default is the same as the annotation method name
      • The @bean annotation defaults to the Singleton Scope, which can be set to the object Scope via @Scope(“prototype”)
  • @ComponentScan

    • Equivalent to context: Component-scan label

    • Component scanner scans classes annotated by @Component, @Controller, @Service, and @Repository

    • This annotation is written on top of the class and is usually used in conjunction with the @Configuration annotation

    • attribute

      • BasePackages: Specifies the packages to scan
      • Value: Same as basePackages
  • @PropertySource

    • Equivalent to context:property-placeholder tag

    • Written on the class to load the Properties configuration file

    • attribute

      • Value [] : specifies the path of the properties file. If it is in the classpath, you need to write the classpath
  • @Import

    • Equivalent to a tag in a Spring configuration file

    • It is used to combine multiple Configuration classes. When introducing other Configuration classes, you do not need to write @configuration annotation again. If you do, there is no problem

    • attribute

      • Value: A bytecode file used to specify other configuration classes