Spring is based on XML / annotation / automatic assembly

Posted by Hoppus on Tue, 08 Mar 2022 02:51:44 +0100

1, Spring assembles beans based on XML

The assembly of beans can be understood as dependency injection. The assembly method of beans is also the dependency injection method of beans. Spring The container supports various forms of Bean assembly, such as XML based Bean assembly, Annotation based Bean assembly and automatic assembly.
Spring XML based assembly usually adopts two implementation methods, namely Setter Injection and Constructor Injection. This section explains how to use these two injection methods in XML configuration files.
When Spring instantiates a Bean, it will first call the default constructor to instantiate the Bean object, and then use the Java The reflection mechanism of calls setXxx() method to inject attributes. Therefore, set value injection requires that the corresponding class of a Bean must meet the following two requirements.

A. a default parameterless construction method must be provided.

B. the corresponding setter method must be provided for the attribute to be injected.

When using set value injection, in the Spring configuration file, you need to inject values for each attribute using the < property > element, a child element of the < bean > element.

When using construction injection, in the configuration file, the < constructor Arg > tag is mainly used to define the parameters of the construction method, and its value attribute (or sub element) can be used to set the value of the parameter.

The following is a case to demonstrate the assembly of beans based on XML for different types of data.

             1. Create a project, improve the structure and import dependencies

             2. Create ClassBean class

package com.wangxing.springdemo6;

/**
 * Practice set injection (property) and construct arg
 */
public class ClassBean {
    private String classcode;
    private String classname;

    public String getClasscode() {
        return classcode;
    }

    public void setClasscode(String classcode) {
        this.classcode = classcode;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }
}

 3. Create StudentBean class

package com.wangxing.springdemo6;

import java.util.*;

public class StudentBean {
    //Basic data type
    private int intVal;
    private double doubleVal;
    private char charVal;
    private boolean booleanVal;
    //String
    private String stringVal;
    //Time date type
    private Date dateVal;
    //Object type
    private ClassBean classBeanVal;
    //array
    private String[] stringArrayVal;
    private ClassBean[] classBeansVal;
    //List
    private List<String> stringListVal;
    private List<ClassBean> classBeanListVal;
    //Set
    private Set<String> stringSetVal;
    private Set<ClassBean> classBeanSetVal;

    public Set<String> getStringSetVal() {
        return stringSetVal;
    }

    public void setStringSetVal(Set<String> stringSetVal) {
        this.stringSetVal = stringSetVal;
    }

    public Set<ClassBean> getClassBeanSetVal() {
        return classBeanSetVal;
    }

    public void setClassBeanSetVal(Set<ClassBean> classBeanSetVal) {
        this.classBeanSetVal = classBeanSetVal;
    }

    //Map
    private Map<String,String> stringMapVal;
    private Map<String,ClassBean> stringClassBeanMap;
    //Properties
    private Properties propertiesVal;

    public int getIntVal() {
        return intVal;
    }

    public void setIntVal(int intVal) {
        this.intVal = intVal;
    }

    public double getDoubleVal() {
        return doubleVal;
    }

    public void setDoubleVal(double doubleVal) {
        this.doubleVal = doubleVal;
    }

    public char getCharVal() {
        return charVal;
    }

    public void setCharVal(char charVal) {
        this.charVal = charVal;
    }

    public boolean isBooleanVal() {
        return booleanVal;
    }

    public void setBooleanVal(boolean booleanVal) {
        this.booleanVal = booleanVal;
    }

    public String getStringVal() {
        return stringVal;
    }

    public void setStringVal(String stringVal) {
        this.stringVal = stringVal;
    }

    public Date getDateVal() {
        return dateVal;
    }

    public void setDateVal(Date dateVal) {
        this.dateVal = dateVal;
    }

    public ClassBean getClassBeanVal() {
        return classBeanVal;
    }

    public void setClassBeanVal(ClassBean classBeanVal) {
        this.classBeanVal = classBeanVal;
    }

    public String[] getStringArrayVal() {
        return stringArrayVal;
    }

    public void setStringArrayVal(String[] stringArrayVal) {
        this.stringArrayVal = stringArrayVal;
    }

    public ClassBean[] getClassBeansVal() {
        return classBeansVal;
    }

    public void setClassBeansVal(ClassBean[] classBeansVal) {
        this.classBeansVal = classBeansVal;
    }

    public List<String> getStringListVal() {
        return stringListVal;
    }

    public void setStringListVal(List<String> stringListVal) {
        this.stringListVal = stringListVal;
    }

    public List<ClassBean> getClassBeanListVal() {
        return classBeanListVal;
    }

    public void setClassBeanListVal(List<ClassBean> classBeanListVal) {
        this.classBeanListVal = classBeanListVal;
    }

    public Map<String, String> getStringMapVal() {
        return stringMapVal;
    }

    public void setStringMapVal(Map<String, String> stringMapVal) {
        this.stringMapVal = stringMapVal;
    }

    public Map<String, ClassBean> getStringClassBeanMap() {
        return stringClassBeanMap;
    }

    public void setStringClassBeanMap(Map<String, ClassBean> stringClassBeanMap) {
        this.stringClassBeanMap = stringClassBeanMap;
    }

    public Properties getPropertiesVal() {
        return propertiesVal;
    }

    public void setPropertiesVal(Properties propertiesVal) {
        this.propertiesVal = propertiesVal;
    }

}

4. Create profile

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

    <!--establish SimpleDateFormat object-->
    <!--SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")-->
    <bean id="simpleDateFormat" class="java.text.SimpleDateFormat">
        <!--Construction method injection-->
        <constructor-arg index="0" value="yyyy-MM-dd"></constructor-arg>
    </bean>

    <!--establish ClassBean-->
    <bean class="com.wangxing.springdemo6.ClassBean" id="classBean1">
        <!--towards classBean Property injection data value in-->
        <property name="classcode" value="20210413-1"></property>
        <property name="classname" value="java Class 1"></property>
    </bean>
    <bean class="com.wangxing.springdemo6.ClassBean" id="classBean2">
        <!--towards classBean Property injection data value in-->
        <property name="classcode" value="20210413-2"></property>
        <property name="classname" value="java Class 2"></property>
    </bean>
    <bean class="com.wangxing.springdemo6.ClassBean" id="classBean3">
        <!--towards classBean Property injection data value in-->
        <property name="classcode" value="20210413-3"></property>
        <property name="classname" value="java Class 3"></property>
    </bean>
    <!--establish StudentBean class-->
    <bean id="studentBean" class="com.wangxing.springdemo6.StudentBean">
        <!--Basic data type-->
        <property name="intVal" value="1001"/>
        <property name="doubleVal" value="168.5"/>
        <property name="charVal" value="A"/>
        <property name="booleanVal" value="true"/>
        <!--String-->
        <property name="stringVal" value="zhangsan"/>
        <!--Date-->
        <property name="dateVal">
            <bean factory-bean="simpleDateFormat" factory-method="parse">
                <constructor-arg index="0" value="2021-04-10"></constructor-arg>
            </bean>
        </property>
        <!--Object-->
        <property name="classBeanVal" ref="classBean1"/>
        <!--String Array-->
        <property name="stringArrayVal">
            <list>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
            </list>
        </property>
        <!--Object Array-->
        <property name="classBeansVal">
            <list>
                <ref bean="classBean1"></ref>
                <ref bean="classBean2"></ref>
                <ref bean="classBean3"></ref>
            </list>
        </property>

        <!--String list-->
        <property name="stringListVal">
            <list>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
            </list>
        </property>
        <!--Object list-->
        <property name="classBeanListVal">
            <list>
                <ref bean="classBean1"></ref>
                <ref bean="classBean2"></ref>
                <ref bean="classBean3"></ref>
            </list>
        </property>
        <!--String Set-->
        <property name="stringSetVal">
            <set>
                <value>zhangsan</value>
                <value>wangwu</value>
                <value>lisi</value>
            </set>
        </property>
        <!--Object Set-->
        <property name="classBeanSetVal">
            <set>
                <ref bean="classBean1"></ref>
                <ref bean="classBean2"></ref>
                <ref bean="classBean3"></ref>
            </set>
        </property>
        <!--String Map-->
        <property name="stringMapVal">
            <map>
                <entry key="name1" value="zhangsan"/>
            </map>
        </property>
        <!--Object Map-->
        <property name="stringClassBeanMap">
            <map>
                <entry key="objMap1" value-ref="classBean1"/>
                <entry key="objMap2" value-ref="classBean2"></entry>
                <entry key="objMap3" value-ref="classBean3"></entry>
            </map>
        </property>
        <!--Properties-->
        <property name="propertiesVal">
            <props>
                <prop key="mydriver">com.jdbc.mysql.Driver</prop>
                <prop key="myurl">jdbc:mysql://127.0.0.1:3306/test</prop>
                <prop key="myname">root</prop>
                <prop key="mypassword">123456</prop>
            </props>
        </property>

    </bean>
</beans>

5. Test

package com.wangxing.springdemo6;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.*;

public class TestMain {
    @Test
    public void test1(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Bean.xml");
        StudentBean studentBean = applicationContext.getBean("studentBean", StudentBean.class);
        /*Basic data type*/
        System.out.println("intval=="+studentBean.getIntVal());
        System.out.println("doubleval=="+studentBean.getDoubleVal());
        System.out.println("charval=="+studentBean.getCharVal());
        System.out.println("booleanval=="+studentBean.isBooleanVal());
        /*String*/
        System.out.println("stringval=="+studentBean.getStringVal());
        /*date*/
        System.out.println("dateval=="+studentBean.getDateVal());
        /*Object*/
        ClassBean classBeanVal = studentBean.getClassBeanVal();
        System.out.println("classBeancode=="+classBeanVal.getClasscode()+"=="+classBeanVal.getClassname());
        /*String Array*/
        System.out.println("-------------------------------------");
        System.out.println("String array");
        for (String string :studentBean.getStringArrayVal()){
            System.out.println("String array--"+string);
        }
        /*Object Array*/
        System.out.println("--------------------------------------");
        System.out.println("Object array");
        for (ClassBean classBean : studentBean.getClassBeansVal()){
            System.out.println("ObjectArray=="+classBean.getClasscode()+"=="+classBean.getClassname());
        }
        /*String List*/
        System.out.println("----------------------------------------");
        System.out.println("String-List");
        for (String strlist:studentBean.getStringListVal()){
            System.out.println( "Strinf- List=="+strlist);
        }
        /*Object List*/
        System.out.println("---------------------------------------");
        System.out.println("Object List");
        for (ClassBean classBean:studentBean.getClassBeanListVal()){
            System.out.println("Object-List=="+classBean.getClasscode()+"=="+classBean.getClassname());
        }
        /*Object-Set*/
        System.out.println("------------------------------------------");
        System.out.println("Object-Set");
        for (ClassBean classBeanset:studentBean.getClassBeanSetVal()){
            System.out.println("Object-Set=="+classBeanset.getClasscode()+"=="+classBeanset.getClasscode());
        }
        /*String-Map*/
        System.out.println("--------------------------------------------");
        System.out.println("String-Map");
        for (Map.Entry<String,String> stringMap:studentBean.getStringMapVal().entrySet()){
            System.out.println("String-Map=="+stringMap.getKey()+":"+stringMap.getValue());
        }
        /*Object-Map*/
        System.out.println("--------------------------------------------");
        System.out.println("Object-Map");
        for (Map.Entry<String,ClassBean> classBeanEntry:studentBean.getStringClassBeanMap().entrySet()){
            System.out.println("Object-Map=="+classBeanEntry.getKey()+":"+classBeanEntry.getValue().getClasscode()+"=="+classBeanEntry.getValue().getClassname());
        }

        /*Properties*/
        System.out.println("--------------------------------------------");
        System.out.println("Properties");
        Properties propertiesVal = studentBean.getPropertiesVal();
//        Set<String> strings = propertiesVal. stringPropertyNames();// Encapsulate all the obtained Key values into the set set
        Iterator<String> prokeys = propertiesVal.stringPropertyNames().iterator();
        while (prokeys.hasNext()){
            String keyval = prokeys.next();
            String mayname = propertiesVal.getProperty(keyval);
            System.out.println("Properties=="+keyval+":"+mayname);
        }


    }
}

2, Spring assembles beans based on Annotation

In Spring In, although the assembly of beans can be realized by using XML configuration files, if there are a large number of beans in the application, the XML configuration files will be too bloated, which will bring some difficulties to maintenance and upgrading.
        Java After JDK 5.0, it provides Annotation function, and spring also provides comprehensive support for Annotation technology. Spring 3 defines a series of annotations. Common annotations are as follows.

   1)@Component

This annotation can be used to describe beans in Spring, but it is a generalized concept that represents only one component (Bean) and can act at any level. When using, you only need to mark the annotation on the corresponding class.

@Component -- the name of the Bean class created with @ component by default, with lowercase initial

@Component(name) -- the specified name

    2)@Repository

The class used to identify the data access layer (DAO layer) as a Bean in Spring has the same function as @ Component.

@Repository -- the name of the Bean class created by @ repository is used by default, with lowercase initial

@Repository(name) -- the specified name

 

      3)@Service

It usually acts on the business layer (Service layer) and is used to identify the class of the business layer as a Bean in Spring. Its function is the same as @ Component.

@Service -- the name of the Bean class created by @ service by default, with lowercase initial

@Service(name) -- specified name

 

     4)@Controller

It usually acts on the control layer (e.g Struts2 Action / controller class of Spring MVC), which is used to identify the class of the control layer as a Bean in Spring, and its function is the same as @ Component.

@Controller -- the name of the Bean class created by @ controller by default, with lowercase initial

@Controller(name) -- specified name

     5)@Autowired

It is used to label the attribute variables, Set methods and constructors of the Bean, and cooperate with the corresponding annotation processor to complete the automatic configuration of the Bean. By default, it is assembled according to the type of Bean.

     6)@Resource

Its function is the same as Autowired. The difference is that @ Autowired is assembled according to the Bean type by default, while @ Resource is assembled according to the Bean instance name by default.
@There are two important attributes in a 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, the assembly is performed by the instance name; If the type attribute is specified, it is assembled by Bean type.
If none is specified, assemble according to the Bean instance name first. If it cannot match, assemble according to the Bean type again; If none of them can match, a NoSuchBeanDefinitionException is thrown.

    7)@Qualifier

When used in conjunction with the @ Autowired annotation, the default assembly by Bean type will be modified to an instance by Bean

1. Create a project, improve the structure and import dependencies

2. Create data access layer implementation class

package com.wangxing.springdemo7.dao;

import org.springframework.stereotype.Component;

/**
 * Operation class of data access layer
 */
@Component("studentDao")
public class StudentDaoImpl {
    public void insertStudent(){
        System.out.println("Adding method of data access layer");
    }
}

3. Create a business access layer implementation class

package com.wangxing.springdemo7.service;

import com.wangxing.springdemo7.dao.StudentDaoImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Operation class of business access layer
 */
@Component("studnetService")
public class StudentServiceImpl {
    @Resource//Automatic type injection is assembled by Bean instance name by default.
    private StudentDaoImpl studentDao;
    public void  apperndStudent(){
        System.out.println("Adding method of business access layer");
        studentDao.insertStudent();
    }
}

4. Create control layer implementation class

package com.wangxing.springdemo7.controller;

import com.wangxing.springdemo7.service.StudentServiceImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Control layer operation class
 */
@Component("studentController")
public class StudnetController {
   // @Autowired / / assemble according to Bean type by default
   @Resource
    private StudentServiceImpl studentService;
    public void addStudent(){
        System.out.println("Control layer adding method");
        studentService.apperndStudent();
    }


}

5. Create Spring configuration file

<?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
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!--use context Namespace, notification spring Scan the specified directory for annotation parsing-->
    <context:component-scan base-package="com.wangxing.springdemo7"></context:component-scan>
</beans>

6. Test

package com.wangxing.springdemo7;

import com.wangxing.springdemo7.controller.StudnetController;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    @Test
    public  void test(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudnetController studentController = applicationContext.getBean("studentController", StudnetController.class);
        studentController.addStudent();
    }
}

3, Spring auto assemble Bean

In addition to using XML and Annotation to assemble beans, there is also a common assembly method - automatic assembly. Automatic assembly means Spring The container can automatically assemble the association relationship between cooperative beans and inject one Bean into the properties of other beans.
To use auto assembly, you need to configure the autowire attribute of the < bean > element. The autowire attribute has five values, as shown in Table 1.

Table 1 Properties and functions of autowire

name

explain

byName

Automatically assemble according to the name of the Property. If the name of a Bean is the same as that of a Property in another Bean, the Bean will be automatically assembled into the Property.

byType

It is automatically assembled according to the data Type of Property. If the data Type of one Bean is compatible with the data Type of Property in another Bean, it is automatically assembled.

constructor

According to the data type of the parameters of the construction method, carry out the automatic assembly of byType mode.

autodetect

If the default construction method is found, use the constructor mode, otherwise use the byType mode.

no

By default, automatic assembly is not used, and Bean dependencies must be defined through the ref element.

1. Create a project, improve the structure and import dependencies

2. Create data access layer implementation class

package com.wangxing.springdemo8.dao;



/**
 * Data access layer implementation class
 */

public class UserDaoImpl {
    public void insertUser(){
        System.out.println("Data access layer adding method");
    }
}

3. Create a business access layer implementation class

package com.wangxing.springdemo8.service;

import com.wangxing.springdemo8.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Business access layer implementation class
 */

public class UserServiceImpl {

    private UserDaoImpl userDaoImpl;

    public void setUserDaoImpl(UserDaoImpl userDaoImpl) {
        this.userDaoImpl = userDaoImpl;
    }

    public UserDaoImpl getUserDaoImpl(){
         return userDaoImpl;
     }

     public void  appenUser(){
         System.out.println("Business access layer adding method");
         userDaoImpl.insertUser();
     }
}

4. Create control layer implementation class

package com.wangxing.springdemo8.controller;

import com.wangxing.springdemo8.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Control layer implementation class
 */
public class UserController {

    private UserServiceImpl userServiceImpl;

    public UserServiceImpl getUserServiceImpl() {
        return userServiceImpl;
    }

    public void setUserServiceImpl(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    public  void addUser(){
        System.out.println("Control layer adding method");
        userServiceImpl.appenUser();
    }
}

5. Create Spring configuration file

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


    <bean id="userController" class="com.wangxing.springdemo8.controller.UserController" autowire="byType">

    </bean>

    <bean autowire="byType" id="userService" class="com.wangxing.springdemo8.service.UserServiceImpl">

    </bean>

    <bean id="userDao" class="com.wangxing.springdemo8.dao.UserDaoImpl">

    </bean>


</beans>

 

Topics: Java Spring