Introduction to Spring and control inversion

Posted by aircooled57 on Fri, 21 Jan 2022 04:34:23 +0100

Reproduced in Li Jian's blog http://www.lijian4net.work/article/68

spring advantages

1. Convenient decoupling and simplified development
2. AOP programming support
3. Declarative support
4. Facilitate program testing
5. Convenient integration of various excellent frameworks
6. Reduce the difficulty of using Java EE API
7. Source code is a classic learning example

Program coupling

Coupling: dependencies between programs
 include:
    Dependencies between classes
    Dependencies between methods
 Decoupling:
    Reduce dependencies between programs
 In the actual development process:
    The compiler does not depend on it, but only when it runs

Bean: in computer English, it means reusable component
JavaBean s: reusable components written in the Java language

spring's IOC core container

Three common implementation classes of ApplicationContext:
ClassPathXmlApplicationContext: it can load the configuration file under the classpath. It is required that the configuration file must be under the classpath. If it is not, it cannot be loaded
FileSystemXmlApplicationContext: it can load configuration files under any path on the disk (must have access rights)
AnnotationConfigApplicationContext: it is used to read annotations and create containers

Two interfaces of the core container:
ApplicationContext: the singleton object is applicable
When creating the core container, the strategy of creating objects is to load immediately. As soon as the configuration file is read, the objects configured in the configuration file will be created immediately
BeanFactory: applicable to multiple objects
When it creates the core container, the strategy of creating objects is to use the method of delayed loading. When the objects are obtained according to the id and when the objects are really created

1. xml based configuration

The basic structure is as follows

<?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">
		<!-- Label content -->
</beans>

After beans is spring constraint, and label content is spring configuration content

1.1 three ways to create bean s

a. The first method is to use the default constructor to create a bean object. After the bean tag is used in the spring configuration file with id and class attributes, when there are no other attributes and tags, the default constructor is used to create a bean object. At this time, if there is no default constructor, the object cannot be created

<bean id="userDao" class="work.lijian4net.www.dao.impl.UserDaoImpl"></bean>

b. The second way: create objects using methods in a normal factory (create objects using methods in a class and store them in the spring container)

<bean id="instanceFactory" class="work.lijian4net.www.factory.InstanceFactory"></bean>
        <bean id="userDao" factory-bean="instanceFactory" factory-method="getUserDao"></bean>
public class InstanceFactory {
	public IUserDao getUserDao(){
		return new UserDaoImpl();
	} 
}

c. The third method: use the static method in the factory to create the object (use some kind of static method to create the object and store it in the spring container

<bean id="userDao" class="work.lijian4net.www.factory.InstanceFactory" factory-method="getUserDao"></bean>
public class InstanceFactory {
	public static IUserDao getUserDao(){
		return new UserDaoImpl();
	} 
}

1.2 scope of bean object

    scope Properties:
        effect:Used to specify bean Scope of action
        Value: common simple interest and multiple cases
            singleton: Singleton (default)
            prototype: Multiple cases
            request: act on web Application request scope
            session: act on web Reply range of application
            global-session:The call back range (global call back range) that acts on the cluster environment. When it is not a cluster environment, it is session

1.3 declaration cycle of bean object

    Singleton object
        Birth: the object is born when the container is created
        Alive: the object is alive as long as the container is still there
        Death: the container is destroyed and the object dies
        Summary: the declaration cycle of the singleton object is the same as that of the container
    Multiple objects:
        Birth: when we use objects, spring Frame creation object
        Alive: the object has been in use and has been alive
        Death: when an object tries not to use and there is no other object reference, Java Garbage collector collection

1.4 dependencies in spring

	Dependency injection: Dependency Injection
    IOC Role of:
        Reduce coupling (dependencies) between programs
    The management of dependencies will be left to the spring To maintain
    Objects of other classes need to be used in the current class. There are spring For us, we only need to specify in the configuration file
    Dependency maintenance:
        This is called dependency injection
    Data that can be injected: three types
        Basic types and String
        other bean Type (configured in configuration file or annotation) bean)
        Complex type/Collection type
    Injection methods: Three
        Use constructor to provide
        use set Method provision
        Use annotation to provide

1.4.1 constructor injection

    Labels used: constructor-arg
    Where the label appears: bean Inside of label
    Attributes in Tags
        type: Specifies the data type of the data to be injected, which is also the type of one or some parameters in the constructor
        index: Used to specify the data to be registered and assign a value to the parameter specifying the index position in the constructor,Parameter index position starts at 0
        name:Used to assign a value to the parameter with the specified name in the constructor (common)
        ==================The above three are used to assign values to which parameter==============
        value:Used to provide basic types and String Type of data
        ref:Used to specify other bean Type of data refers to spring of ioc In the core container bean object

 Advantages:
    In getting bean Object, injecting data is a necessary operation, otherwise the object cannot be created
 Disadvantages:
    Changed bean The instantiation method of objects makes it necessary to provide these data when creating objects
    <bean id="userService1" class="work.lijian4net.www.service.impl.UserServiceImpl">
        <constructor-arg type="java.lang.String" value="test"></constructor-arg>
        <constructor-arg name="age" value="12"></constructor-arg>
        <constructor-arg index="2" ref="now"></constructor-arg>
    </bean>

    <!--Configure a date object-->
    <bean id="now" class="java.util.Date"></bean>
public class UserServiceImpl implements IUserService {

    private IUserDao userDao = new UserDaoImpl();

    //For frequently changing data, it is not applicable to the injection method
    private String name;
    private Integer age;
    private Date birthday;

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

    }

    @Override
    public boolean Save(User user) {
        try{
            return userDao.insert(user)>0;
        }catch (Exception ex){
            System.out.println(ex.getMessage());
            return false;
        }
    }
}

1.4.2 set method injection is more commonly used

Labels involved: property
 Location of occurrence: bean Inside of label
 Label properties:
	name:Used to specify the called by injection set Method name
	value:Used to provide basic types and String Type of data
	ref:Used to specify other bean Type of data refers to spring of ioc In the core container bean object
 Advantages:
	There are no explicit restrictions when creating objects. You can directly use the default constructor
 Disadvantages:
	If a member must also be called, it is possible to get the object set Method not executed
<bean id="userService2" class="work.lijian4net.www.service.impl.UserServiceImpl2">
	<property name="name" value="test"></property>
	<property name="age" value="12"></property>
	<property name="birthday" ref="now"></property>
</bean>
public class UserServiceImpl2 implements IUserService {

    private IUserDao userDao = new UserDaoImpl();

    //For frequently changing data, it is not applicable to the injection method
    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;
    }

    @Override
    public boolean Save(User user) {
        try{
            return userDao.insert(user)>0;
        }catch (Exception ex){
            System.out.println(ex.getMessage());
            return false;
        }
    }
}

1.4.3 complex type / set type injection

    Used to give List Label injected by structure set:
        list array set
    Used to give Map Label injected by structure set:
        map props
    The structure is the same, and the labels can be interchanged
 <bean id="userService3" class="work.lijian4net.www.service.impl.UserServiceImpl3">
        <property name="myStrs">
            <array>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
        <property name="mySet">
            <set>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </set>
        </property>
        <property name="myMap">
            <map>
                <entry key="aaa" value="aaaaa"></entry>
                <entry key="bbb">
                    <value>bbbbbbbb</value>
                </entry>
            </map>
        </property>
        <property name="myProps">
            <props>
                <prop key="aaa">cacac</prop>
                <prop key="bbb">cbcbc</prop>
            </props>
        </property>
    </bean>
public class UserServiceImpl3 implements IUserService {
    

    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;
    }

    @Override
    public boolean Save(User user) {
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);


        return false;
    }
}

2 annotation based configuration

Previous XML configuration

    <bean id="userDao" class="work.lijian4net.www.factory.InstanceFactory"
       scope="" init-method="" destroy-method="">
       <property name="" value="" / ref=""></property>
    </bean>

2.1 for creating objects

   Their role and in xml Write one in the configuration file<bean></bean>The functions implemented by the tag are the same
   Component: 
       Function: used to save the current class into spring In container
       Properties:
           value: Used to specify bean of id,When we do not write, the default is the current class name, and the initial letter is changed to lowercase
   Controller: Generally used for presentation layer
   Serivce: It is generally used in the business layer
   Respository: Generally used in persistence layer
   The functions and of the above three notes Component They are as like as two peas, and the three of them are spring The framework provides us with explicit annotations for three-tier use, making our three-tier objects clearer

2.2 for injecting data

   Their role is the same as in xml In the configuration file bean Write one in the label<property></property>The function of the label is the same
   Autowired
       Function: automatically inject by type, as long as there is a unique one in the container bean If the object type matches the variable type to be injected, the injection can be successful
               If IOC There is no in the container bean If the type of matches the type of the variable to be injected, an error is reported.
               If IOC When multiple types match in the container:
       Location:
           It can be variable or method
       Details: when using annotation injection, set The method is not necessary
   Qualifier: 
       Function: inject by name based on the injection in class. It cannot be used alone when injecting class members. However, when injecting method parameters, you can
       Properties:
           value: Used to specify injection bean of id
   Resource
       Function: direct safety bean of id Injection. It can be used independently
       Properties:
           name: Used to specify bean of id
   The above three injections can only inject other injections bean Type of data, while the basic type and String Type cannot be implemented with the above annotation
   In addition, the injection of collection type can only be through xml To achieve
   Value
        Function: for implantation of basic types and String Type of data
        Properties:
            value: Used to specify the value of the data, which can be used spring Medium SpEL(spring of el (expression)
                    SpEL How to write: ${expression}

2.3 for changing the scope of action

   Their role is the same as in bean Used in labels scope The function of the label is the same
   Scope
        Role: used to specify bean Scope of action
        Properties:
            value: Specifies the value of the range. Common values: singleton prototype
 Related to the declaration cycle (understand)
   Their role is the same as in bean Used in labels init-method and destory-method Labels work the same way
    PreDestory
        Function: used to specify the destruction method
    PostConstruct
        Function: used to specify the initialization method
@Repository(value = "annoDao")
public class AnnoDaoImpl implements IAnnoDao {

    @Override
    public void save(User user) {
        
    }
}

Topics: Java Spring