Java day 38, Spring framework series, dependency injection -- profile injection

Keywords: Spring Java xml encoding

1, What is dependency injection

Dependency management is managed and maintained by the spring framework. Other class resources needed by the current class are provided by spring. We only need to declare them in the configuration file. The maintenance of dependency is called dependency injection

2, Types of data that can be injected

  • Basic types and strings
  • True bean type (configured bean in configuration file or annotation)
  • Complex type / set type

3, How to inject

  • Using the constructor to provide
  • Using set method to provide
  • Using annotations to provide

Note: when the three injection methods are injected with specific values, it doesn't matter whether the double quotes (string ID) are written or not, because spring always treats the initial value of the injection as a string type

4, Constructor injection method

Construction method injection requires that each member property of a class must have a value

1. Tutorial

The < constructor Arg > < constructor Arg > internal label declaration using the < bean > < bean > tag

<bean id="" class="">
        <constructor-arg [option]="" value=""></constructor-arg>   
        < constructor Arg [option] = "ref =" [custom beanid] "> < / constructor Arg >
</bean>
< bean id = "[custom bean ID]" class = "fully qualified class name" > < / bean >


1. The optional parameters in option are as follows:
Type = = > used to specify the data type of the data to be injected, which is also the type of one or some parameters in the constructor (not applicable to constructors with multiple parameters of the same type)
Index = = > used to specify the data to be injected to assign a value to the parameter in the constructor that specifies the index position. Index location starts from 0 (not commonly used)
Name = = > parameter assignment for the specified name in the constructor (common)

2.
Value represents the value assigned to the parameter specified in step 1;
When assigning a value, all values are regarded as strings. Some types can be converted by spring intelligence, and some can't, such as Date type. So we need ref
 3.ref is used to cooperate with constructor Arg tag to complete the conversion of parameter types that spring cannot intelligently convert

2. Examples

Class of injected data

package com.huhai.Dao.Impl;

import com.huhai.Dao.IAccountDao;

import java.util.Date;

/**
 * Persistence layer implementation class
 */
public class AccountDaoImpl implements IAccountDao {

    private String name;
    private Integer activeDays;
    private Date activeDate;

    public AccountDaoImpl(String name, Integer activeDays, Date activeDate) {
        this.name = name;
        this.activeDays = activeDays;
        this.activeDate = activeDate;
    }

    public void save() {
        System.out.println(name + " " + activeDate + " " + activeDays);
    }
}
<?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">

    <!--Give object creation to spring To manage-->
    <bean id="accountServiceImpl" class="com.huhai.Service.Impl.AccountServiceImpl"></bean>

    <bean id="accountDaoImpl" class="com.huhai.Dao.Impl.AccountDaoImpl">
        <constructor-arg name="name" value="lanyue"></constructor-arg>
        <constructor-arg name="activeDays" value="100"></constructor-arg>
        <constructor-arg name="activeDate" ref="myDate"></constructor-arg>
    </bean>
    <!--Corresponding to the above ref Parameter points to myDate-->
    <bean id="myDate" class="java.util.Date"></bean>

</beans>

5, set method injection mode

The set method cannot guarantee that every member property of the injected class must have a value

1. Tutorial

① First, the set method is generated in the injected class

② Using the inner tag of < bean > < bean > tag < property > < property > to inject data for class properties

Parameters:
1. Name = = > parameter assignment for the specified name in the constructor (common)
2.value represents the value assigned to the parameter specified in step 1
 When assigning a value, all values are regarded as strings. Some types can be converted by spring intelligence, and some can't, such as Date type. So we need ref
 3.ref is used to cooperate with constructor Arg tag to complete the conversion of parameter types that spring cannot intelligently convert

<bean id="" class="">
        <! -- the value of the name parameter is only related to the set method, but not to the property name to be set by the set method -- >
        <property name="" value=""></property>
        <! -- if the set parameter cannot meet the requirements, the ref parameter is required -- >
        < property name = "" ref = "[reference ID]" > < / property >
</bean>

< bean id = "referenced ID" class = "" > < bean >

2. Examples

Injected class

package com.huhai.Dao.Impl;

import com.huhai.Dao.IAccountDao;

import java.util.Date;

/**
 * Persistence layer implementation class
 */
public class AccountDaoImpl implements IAccountDao {

    private String name;
    private Integer activeDays;
    private Date activeDate;

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

    public void setActiveDays(Integer activeDays) {
        this.activeDays = activeDays;
    }

    public void setActiveDate(Date activeDate) {
        this.activeDate = activeDate;
    }

    public void save() {
        System.out.println(name + " " + activeDate + " " + activeDays);
    }
}

Profile to inject class data

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

    <!--Give object creation to spring To manage-->
    <bean id="accountServiceImpl" class="com.huhai.Service.Impl.AccountServiceImpl"></bean>

    <!--set Method injection mode-->
    <bean id="accountDaoImpl" class="com.huhai.Dao.Impl.AccountDaoImpl">
        <property name="name" value="limited company"></property>
        <property name="activeDate" ref="myDate"></property>
        <property name="activeDays" value="200"></property>
    </bean>
    <bean id="myDate" class="java.util.Date"></bean>


</beans>

6, Compound / complex / set type injection mode

This method must select one of the set method or construction method as the basic injection method, and then use the sub label < array / > < list / > < map / > in < property / > or < constructor Arg > to inject

1. Steps

① Generate the construction method or set method with parameters

② Based on the construction method injection mode or set method injection mode, the combination of the two sub tags is used for injection

2. Examples

package com.huhai.Dao.Impl;

import com.huhai.Dao.IAccountDao;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Persistence layer implementation class
 */
public class AccountDaoImpl implements IAccountDao {

    private String[] myStr;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String, String> myMap;
    private Properties myPro;

    public void setMyStr(String[] myStr) {
        this.myStr = myStr;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyPro(Properties myPro) {
        this.myPro = myPro;
    }

    public void save() {
        System.out.println(Arrays.toString(myStr));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myPro);
    }
}
<?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">

    <!--Give object creation to spring To manage-->
    <bean id="accountServiceImpl" class="com.huhai.Service.Impl.AccountServiceImpl"></bean>

    <!--set Method injection mode-->
    <bean id="accountDaoImpl" class="com.huhai.Dao.Impl.AccountDaoImpl">
        <property name="myStr">
            <array>
                <value>"first"</value>
                <value>"the second"</value>
                <value>"Third"></value>
            </array>
        </property>

        <property name="myList">
            <list>
                <value>"first"</value>
                <value>"the second"</value>
                <value>"Third"></value>
            </list>
        </property>

        <property name="mySet">
            <set>
                <value>"first"</value>
                <value>"the second"</value>
                <value>"Third"></value>
            </set>
        </property>

        <property name="myMap">
            <map>
                <!--The first way to write-->
                <entry key="first key" value="first value"></entry>
                <!--The second way of writing-->
                <entry key="the second key">
                    <value>"the second value"</value>
                </entry>
                <entry key="Third key" value="Third value"></entry>
            </map>
        </property>
        
        <property name="myPro">
            <props>
                <prop key="first Key">"first value"</prop>
                <prop key="the second Key">"the second value"</prop>
                <prop key="Third Key">"Third value"</prop>
            </props>
        </property>

    </bean>
    <bean id="myDate" class="java.util.Date"></bean>


</beans>

7, Project architecture

1. Persistence layer interface

package com.huhai.Dao;

/**
 *Persistence layer interface
 */
public interface IAccountDao {
    public abstract void save();
}

2. Persistence layer interface implementation class (code corresponding to different injection methods may be different)

package com.huhai.Dao.Impl;

import com.huhai.Dao.IAccountDao;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Persistence layer implementation class
 */
public class AccountDaoImpl implements IAccountDao {

    private String[] myStr;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String, String> myMap;
    private Properties myPro;

    public void setMyStr(String[] myStr) {
        this.myStr = myStr;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyPro(Properties myPro) {
        this.myPro = myPro;
    }

    public void save() {
        System.out.println(Arrays.toString(myStr));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myPro);
    }
}

3. Business layer interface

package com.huhai.Service;

/**
 *Business layer interface
 */
public interface IAccountService {
    public abstract void save();
}

4. Business layer interface implementation class

package com.huhai.Service.Impl;

import com.huhai.Dao.IAccountDao;
import com.huhai.Service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;

/**
 * Business layer implementation class
 */
public class AccountServiceImpl implements IAccountService {

    public void save() {

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountDao as = ac.getBean("accountDaoImpl", IAccountDao.class);
        as.save();
    }
}

5. Presentation layer

package com.huhai;

import com.huhai.Service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Realize {

    public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = ac.getBean("accountServiceImpl", IAccountService.class);
        as.save();
    }
}

6. Injection profile( bean.xml , the file name is optional) (the configuration file for each injection method is given in the example)

7. Project profile pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>demo13</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

</project>

 

Posted by DarrenReeder on Thu, 18 Jun 2020 19:12:48 -0700