Getting started with Spring IoC

1, How to start the IoC container:

1. Start IoC container in Java environment:

  1. ClassPathXmlApplicationContext: load the configuration file from the root path of the class (recommended);
  2. FileSystemXmlApplicationContext: load the configuration file from the disk path;
  3. AnnotationConfigApplicationContext: start the Spring container in pure annotation mode;

2. Start IoC container in Web Environment:

1) Start the container from xml;

<!DOCTYPE web-app PUBLIC 
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
        "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!-- to configure Spring ioc Configuration file for container --> 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value> 
    </context-param>
    <!-- Start with listener Spring of IOC container -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

2) Launch container from configuration class

<!DOCTYPE web-app PUBLIC 
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    
    <!-- tell ContextloaderListener Know that we start with annotations ioc container --> 
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    
    <!-- Configure the fully qualified class name of the startup class --> 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            com.lagou.edu.SpringConfig
        </param-value> 
    </context-param>
    <!-- Start with listener Spring of IOC container -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

2, Pure xml schema

1. Creation of bean object

The specific contents are put in the notes of the example.

<!-- xml File header -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- instantiation  Bean Three ways of -->
    <!-- Method 1: use parameterless constructor -->
    <!-- By default, it creates objects by calling the parameterless constructor through reflection. If there is no parameterless constructor in the class, the creation fails. -->
    <!-- to configure service object -->
    <bean id="userService" class="com.lagou.service.impl.TransferServiceImpl"></bean>
    
    <!-- Method 2: use static method to create -->
    <!-- In actual development, many object instances can not be created directly through the constructor. It may do a lot of additional operations in the process of creation. -->
    <!-- At this point, a method to create an object will be provided, which happens to be static This is the way of modification. -->
    <!-- How objects are configured using static methods -->
    <bean id="userService" class="com.lagou.factory.BeanFactory" factory-method="getTransferService"></bean>
    
    <!-- Method 3: use instantiation method to create -->
    
    <!--How to configure objects created using the instance method-->
    <!-- The difference between this method and the above static method is that the method used to obtain the object is no longer static static Modified, but a common method in a class. -->
    <!-- This method is more likely to be used than static method creation. -->
    <bean id="beanFactory" class="com.lagou.factory.instancemethod.BeanFactory"></bean>
    <bean id="transferService" factory-bean="beanFactory" factory-method="getTransferService"></bean>
</beans>

2. Dependency injection configuration for object properties

The specific contents are also placed in the notes of the example.

<!-- xml File header -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <!-- Method 1: constructor injection -->
    <!-- As the name suggests, it is to use the constructor to assign values to class members. -->
    <!-- The use requirement is that the number of constructor parameters provided in the class must be consistent with the number of configured parameters, and the data type must match. -->
    <!-- Note that when there is no parameterless construction, the injection of constructor parameters must be provided, otherwise Spring The frame will report an error. -->
    <bean id="transferDao" class="com.lagou.dao.TransferDaoImpl">
        <!-- Constructor use constructor-arg Tag, which has the following properties: -->
        <!-- name: Used to assign a value to the parameter with the specified name in the constructor. -->
        <!-- index: Used to assign a value to the parameter specifying the index position in the constructor. -->
        <!-- value: Used to specify the basic type or String Type of data. -->
        <!-- ref: Used to specify other Bean Type of data. It says something else bean Unique identification of the. -->
        <constructor-arg name="connectionUtils" ref="connectionUtils"/>
        <constructor-arg name="name" value="zhangsan"/>
        <constructor-arg name="sex" value="1"/>
        <constructor-arg name="money" value="100.0"/>
    </bean>
    
    <!-- Mode 2: set Method injection -->
    <!-- As the name suggests, it uses fields set Method to implement the injection mode of assignment. -->
    <!-- This method is the most used injection method in actual development. -->
    <bean id="transferDao" class="com.lagou.dao.TransferDaoImpl">
        <!-- in use set Method injection, you need to use property Tag, whose properties are as follows: -->
        <!-- name: Specifies the method to call when injecting set Method name. (not included) set These three letters) -->
        <!-- value: Specifies the injected data. It supports basic types and String Type. -->
        <!-- ref: Specifies the injected data. It supports other bean Type. It says something else bean Unique identification of the. -->
        <property name="connectionUtils" ref="connectionUtils"/>
        <property name="name" value="zhangsan"/>
        <property name="sex" value="1"/>
        <property name="money" value="100.0"/>
    </bean>
    
    <!-- Method 3: complex data type injection -->
    <!-- It refers to collection type data. Sets are divided into two categories. One is List Structure (array structure), one is Map Interface (key value pair). -->
    <!-- The injection mode is in the constructor and set Method, our example is set Method injection. -->
    <bean id="transferDao" class="com.jason.dao.TransferDaoImpl">
        <!-- String[] myArray -->
        <!-- Key points for attention -->
        <!-- stay List When the collection data of the structure is injected, array,list,set These three labels are common.-->
        <!-- In addition, note value value The value can be written directly inside the tag, or it can be used <bean/> Label to configure an object, or use <ref/> The tag refers to an already matched bean Unique identification of the. -->
        <property name="myArray">
            <array>
                <value>array1</value>
                <value>array2</value>
                <value>array3</value>
            </array>
        </property>

        <!-- Map<String, String> myMap -->
        <!-- Key points for attention -->
        <!-- stay Map When the collection data of the structure is injected, -->
        <!-- map Label use entry The sub tag realizes data injection, entry Labels can be used key and value Property specifies the storage map Data in. -->
        <!-- use value-ref Property specifies the configured bean Reference to. --> 
        <!-- meanwhile entry Labels can also be used ref Label, but cannot be used bean label. -->
        <property name="myMap">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
            </map>
        </property>

        <!-- Set<String> mySet -->
        <property name="mySet">
            <set>
                <value>set1</value>
                <value>set2</value>
            </set>
        </property>

        <!-- Properties myProperties -->
        <!-- Key points for attention -->
        <!-- property Cannot be used in label ref perhaps bean Label reference object. -->
        <property name="myProperties">
            <props>
                <prop key="prop1">value1</prop>
                <prop key="prop2">value2</prop>
            </props>
        </property>
    </bean>
</beans>

3, xml and annotation combination pattern

1. Attention

  1. In actual enterprise development, pure xml schema is rarely used;
  2. The annotation function is introduced without introducing additional jar s;
  3. xml + annotation combination mode, xml files still exist, so the Spring IoC container starts from loading xml;
  4. Which bean definitions are written in xml and which bean definitions use annotations;
    The bean s in the third-party jar are defined in xml, such as the Druid database connection pool;
    Self developed bean definitions use annotations.

2. Correspondence between tags and annotations in xml (IoC)

xml formCorresponding annotation form
bean tag@Component(""), annotated on the class;
The content of the bean id attribute is directly configured after the annotation. If it is not configured, the bean id is the lowercase initial of the class name by default;
In addition, for layered code development, three aliases @ Controller, @ Service and @ Repository of @ Component are provided for bean definitions of control layer class, Service layer class and dao layer class respectively. The usage of these four annotations is exactly the same, just for clearer distinction.
scope property of the label@Scope("prototype"), the default singleton, and annotations are added to the class.
Init method attribute of tag@PostConstruct, annotation is added to the method, which is called after initialization.
Destory method attribute of tag@PreDestory, annotation is added to the method, which is called before destruction.

3. Annotation implementation of DI dependency injection

1) @ Autowired (recommended)

@The annotation provided by Autowired for Spring needs to import the package:
org.springframework.beans.factory.annotation.Autowired.
@The strategy adopted by Autowired is to inject by type.

public class TransferServiceImpl {
    @Autowired
    private AccountDao accountDao;
}

When a class has multiple bean values, it needs to be used with @ Qualifier.
@Qualifier tells Spring which object to assemble.

public class TransferServiceImpl {
    @Autowired
    @Qualifier(name="jdbcAccountDaoImpl")
    private AccountDao accountDao;
}

2)@Resource

@The resource annotation is provided by J2EE and needs to import the package javax annotation. Resource.
@Resource s are automatically injected by ByName by default.

public class TransferService {
    @Resource
    private AccountDao accountDao;
    @Resource(name="studentDao")
    private StudentDao studentDao;
    @Resource(type="TeacherDao")
    private TeacherDao teacherDao;
    @Resource(name="manDao",type="ManDao")
    private ManDao manDao;
}
  • If both name and type are specified, the only matching bean will be found in the Spring context for assembly. If not, an exception will be thrown;
  • If name is specified, the bean with matching name (id) will be found in the context for assembly. If it is not found, an exception will be thrown;
  • If the type is specified, the only bean with similar matching will be found from the context for assembly. If it cannot be found or multiple beans are found, an exception will be thrown;
  • If neither name nor type is specified, the assembly will be performed automatically by byName;

3) Note:

@The Resource has been removed in Jdk 11. If you want to use it, you need to import a jar package separately.

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

4, Pure annotation mode

Transform the xml annotation mode, migrate all the contents left in xml in the form of annotations, delete xml and start from java configuration class.
Corresponding notes:

  • @Configuration annotation, indicating that the current class is a configuration class.
  • @ComponentScan annotation, replacing context: component scan.
  • @PropertySource, which introduces the external property configuration file.
  • @Import to introduce other configuration classes.
  • @Value can be assigned to a variable directly, or ${} can be used to read the information in the resource configuration file.
  • @Bean adds the method return object to the Spring IoC container.

Article content output source: pull hook education Java high salary training camp;

Keywords: Java Spring ioc

Added by numoon56 on Fri, 21 Jan 2022 23:15:01 +0200