Summary of java Summer Vacation Learning (18) - - Spring - DI (Dependency Injection) - - Annotation-based IOC and DI

Keywords: Programming Spring xml encoding Attribute

1. The Concept of Dependency Injection

Dependency injection: Dependency Injection. It is the concrete implementation of spring framework core ioc. When our program is written, the creation of objects is handed over to spring by controlling inversion, but there can be no dependency in the code. IOC decoupling only reduces their dependencies, but it does not eliminate them. For example, our business layer still calls persistence layer methods. This dependency between the business layer and the persistence layer is maintained by spring after using spring. Simply put, it is to wait for the framework to bring persistent layer objects into the business layer, instead of having to acquire them ourselves.

2. Injection mode

 

Data that can be injected: There are three types

  • Basic types and String
  • Other bean types (beans configured in configuration files or annotations)
  • Complex type/collection type

There are three ways of injection
1. First: Provide with constructors
2. The second is to use the set method to provide
3. The third type: using annotations to provide

1. Constructor injection:
Label used: constructor-arg
Location of tags: inside of bean Tags
Attributes in Tags
Type: A data type used to specify the type of data to be injected, which is also the type of a parameter or parameters in the constructor
Index: Used to specify the data to be injected and assign values to the parameters in the constructor that specify the index location. The location of the index starts at 0.
Name: A parameter assignment (commonly used) used to specify a name in a constructor
============= The three above are used to assign values to which parameter in the constructor===============================
value: Data for basic and String types
ref: Used to specify other bean type data. It refers to bean objects that have appeared in spring's Ioc core container.

Advantages:
Injecting data is a necessary operation when acquiring bean objects, otherwise objects cannot be created successfully.
Disadvantages:
Change the way bean objects are instantiated so that when we create objects, we must also provide them if we don't need the data.

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="Tester"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>

Obtained object classes must have a parametric construction method

public class AccountServiceImpl implements IAccountService {

    //If it's constantly changing data, it's not suitable for injection.
    private String name;
    private Integer age;
    private Date birthday;

    public AccountServiceImpl(String name,Integer age,Date birthday){
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void  saveAccount(){
        System.out.println("service Medium saveAccount The method is executed..."+name+","+age+","+birthday);
    }


}

2.set method injection: (more commonly used)
The label involved: property
Location of occurrence: inside the bean tag
Attributes of tags
Name: Used to specify the name of the set method invoked at injection time
value: Data for basic and String types
ref: Used to specify other bean type data. It refers to bean objects that have appeared in spring's Ioc core container.
Advantages:
There are no explicit restrictions when creating objects and you can use the default constructor directly
Disadvantages:
If a member must have a value, it is possible that the set method is not executed.

 <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="TEST" ></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
    </bean>

Object classes acquired should have corresponding set methods

public class AccountServiceImpl2 implements IAccountService {

    //If it's constantly changing data, it's not suitable for injection.
    private String name;
    private Integer age;
    private Date birthday;

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

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public void  saveAccount(){
        System.out.println("service Medium saveAccount The method is executed..."+name+","+age+","+birthday);
    }


}

Injection of Complex Type/Set Type
Labels used to inject a List structure set:
            list array set
Labels for injection into a set of Map structures:
            map  props
The same structure and interchangeable labels

 <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <set>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </set>
        </property>

        <property name="myList">
            <array>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </array>
        </property>

        <property name="mySet">
            <list>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </list>
        </property>

        <property name="myMap">
            <props>
                <prop key="testC">ccc</prop>
                <prop key="testD">ddd</prop>
            </props>
        </property>

        <property name="myProps">
            <map>
                <entry key="testA" value="aaa"></entry>
                <entry key="testB">
                    <value>BBB</value>
                </entry>
            </map>
        </property>
    </bean>

Corresponding classes

public class AccountServiceImpl3 implements IAccountService {

    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myProps;

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    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 setMyProps(Properties myProps) {
        this.myProps = myProps;
    }

    public void  saveAccount(){
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);
    }


}

3. Annotation-based IOC and DI

To learn annotation-based IoC configuration, we must first have a recognition in mind that annotation configuration and xml configuration are to achieve the same function, which is to reduce the coupling between programs. It's just that the configuration is different. Each company has different usage habits about whether to use xml or annotations in actual development. So we need to master these two configurations.

Configuration of xml files

Be sure to tell spring to scan packages when creating containers (otherwise, even with annotations, packages must be scanned correctly). The tags needed for configuration are not in the beans constraints, but are named
context namespaces and constraints

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

    <!--inform spring The package to be scanned when creating the container is not configured with the required label in beans In the constraints, it's a name called
    context Namespaces and constraints-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

Common Notes

1.@Component

   @Component:
* Function: Used to store current class objects in spring containers
* Attributes:
* value: The id used to specify the bean. When we don't write it, its default value is the current class name, and the initials are lowercase.

2.@Controller @Service @Repository

  • @ Controller: Usually used at the presentation level
  • @ Service: Usually used at the business level
  • @ Repository: Usually used in persistence layer

The above three annotations have the same functions and attributes as Component.
The three of them are spring frameworks that provide us with clear annotations for three-tier usage to make our three-tier objects clearer

For injection data (annotations provide injection)
Their role is the same as that of writing a < property > tag in the bean tag in the xml configuration file.

1.@Autowired:
Function: Automatically inject according to type. As long as there is only one bean object type in the container that matches the variable type to be injected, the injection is successful

  • If no bean type matches the variable type to be injected in the ioc container, an error is reported.
  • If there are multiple types matching in the Ioc container, the same id with the name of the corresponding variable will be found, and if not, an error will be reported.

Location of occurrence:
Variable or method
Details:
set methods are not necessary when annotation injection is used.

2.@Qualifier:(Used with Autowire when injecting class members)
Function: Inject by name on the basis of injecting by class. It cannot be used alone when injecting class members. But when injecting method parameters, you can
Attributes:
value: Used to specify the id of the injected bean.

3.@Resource:(Equivalent to @Autowired+@Qualifier)
Function: Inject directly according to the id of the bean. It can be used independently.
Attributes:
name: The id used to specify the bean.
All three injections can only inject data of other bean types, while the basic and String types cannot be implemented with the above annotations.
In addition, the injection of collection type can only be realized through XML.

4.@Value:
Function: Used to inject data of basic type and String type
Attributes:
value: value used to specify data. It can use SpEL in spring (that is, spring's el expression)
SpEL: ${expression}


5.@Scope: (Used to change the scope of action, it works the same as using the scope attribute in the bean tag)
Function: Used to specify the scope of a bean
Attributes:
Value: The value of the specified range. Common values: singleton prototype

Posted by GameSoft on Fri, 26 Jul 2019 05:29:14 -0700