01-SpringIoC&DI

1. Spring overview

1.1 What is Spring (understanding)

Spring is a layered full-stack lightweight open source framework for Java SE/EE applications, with IoC (Inverse Of Control: Inversion of Control) and AOP (Aspect Oriented Programming: Aspect Oriented Programming) as the core.

It provides many enterprise-level application technologies (service) such as presentation layer (web), SpringMVC, persistence layer (dao), Spring JDBCTemplate, and business layer transaction management. The most open source framework for Java EE enterprise applications

1.2 Spring development process (understand)

Rod Johnson (Father of Spring)

The latest version of Spring, Spring 5.0 General Edition (GA)
, was released in September 2017

1.3 Advantages of Spring (understanding)

①Easy decoupling and simplified development

For example, when the service uses the dao layer, it needs to obtain the object of the dao layer. In Spring, we give the creation right of the dao object to Spring, and get it from Spring when we need it.

②AOP programming support

③ Support for declarative transactions

④Convenient program testing

1.4 Architecture of Spring (understanding)

2. Spring Quick Start

2.1 Spring program development steps

① Import the coordinates of the basic package developed by Spring

②Write Dao interface and implementation class

③Create a Spring core configuration file

④Configure UserDaoImpl in the Spring configuration file

⑤ Use Spring’s API to obtain Bean instances

2.2 Import the coordinates of the basic package developed by Spring

<properties>
    <spring.version>5.0.5.RELEASE</spring.version>
</properties>
<dependencies> 
    <dependency>  
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>${spring.version}</version>
    </dependency>
</dependencies>

2.3 Write Dao interface and implementation class

public interface UserDao {  
    public void save();
}

public class UserDaoImpl implements UserDao {  
        @Override  
        public void save() {
            System.out.println("UserDao save method running....");
    }
}

2.4 Create the Spring core configuration file

Create the applicationContext.xml configuration file under the classpath (resources)

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

2.5 Configure UserDaoImpl in the 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="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
</beans>

2.6 Obtaining Bean Instances Using Spring’s API

@Test
public void test1(){
        ApplicationContext applicationContext = new  
             ClassPathXmlApplicationContext("applicationContext.xml");
             UserDao userDao = (UserDao) applicationContext.getBean( "userDao" ); userDao.save();
 }

3. Spring configuration file

3.1 Bean tag basic configuration

Used to configure objects created by Spring.

By default, it calls the no-argument constructor in the class. If there is no no-argument constructor, it cannot be created successfully.

Basic properties:

id: the unique identifier of the bean instance in the Spring container

class: the fully qualified name of the bean

3.2 Bean tag scope configuration

scope: refers to the scope of the object, the values ​​are as follows:

Ranges illustrate
singleton default, singleton
prototype multiple
request In the WEB project, Spring creates a Bean object and stores the object in the request field
session In the WEB project, Spring creates a Bean object and stores the object in the session domain
global session In the WEB project, it is applied in the Portlet environment. If there is no Portlet environment, the globalSession is equivalent to the session.

1) When the value of scope is singleton

​ Number of instantiations of Beans: 1

Bean instantiation timing: When the Spring core file is loaded, instantiate the configured Bean instance

​ Bean life cycle:

Object Creation: Objects are created when the application loads and the container is created

Object running: as long as the container exists, the object is alive

Object destruction: When the application is uninstalled and the container is destroyed, the object is destroyed

2) When the value of scope is prototype

​ Number of instantiations of Beans: multiple

​ Bean instantiation timing: Bean is instantiated when the getBean() method is called

Object creation: when using an object, create a new object instance

Object running: as long as the object is in use, it is alive

Object Destruction: When an object is not used for a long time, it is reclaimed by Java’s garbage collector

3.3 Bean life cycle configuration

init-method: specifies the name of the initialization method in the class

destroy-method: the name of the destruction method in the specified class

3.4 Three ways of Bean instantiation

1) Instantiate using the no-argument constructor

​ It will create a class object according to the default no-argument constructor. If there is no default no-argument constructor in the bean, the creation will fail

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>

2) Factory static method instantiation

​ The static method of the factory returns the Bean instance

public class StaticFactoryBean {
    public static UserDao createUserDao(){    
    return new UserDaoImpl();
    }
}

<bean id="userDao" class="com.itheima.factory.StaticFactoryBean" 
      factory-method="createUserDao" />

3) Factory instance method instantiation

​ The non-static method of the factory returns the Bean instance

public  class  DynamicFactoryBean {   
    public UserDao createUserDao () {        
         return  new UserDaoImpl();
    }
}

<bean id="factoryBean" class="com.itheima.factory.DynamicFactoryBean"/>
<bean id="userDao" factory-bean="factoryBean" factory-method="createUserDao"/>

3.5 Getting Started with Bean Dependency Injection

①Create UserService, UserService internally calls the save() method of UserDao

public class UserServiceImpl implements UserService {
    @Override
    public void save() {
         ApplicationContext applicationContext = new 
                 ClassPathXmlApplicationContext("applicationContext.xml");                     UserDao userDao = (UserDao) applicationContext.getBean("userDao");   
          userDao.save();
    }
 }

② Give the creation right of UserServiceImpl to Spring

<bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>

③ Get UserService from Spring container for operation

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();

3.6 Bean Dependency Injection Concept

Dependency Injection: It is a concrete implementation of the core IOC of the Spring framework.

When writing a program, through inversion of control, the creation of objects is handed over to Spring, but it is impossible to have no dependencies in the code.

IOC decoupling only reduces their dependencies, but does not eliminate them. For example: the business layer will still call the methods of the persistence layer.

The 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 pass the persistence layer object into the business layer, instead of obtaining it ourselves

3.7 Bean dependency injection method

①Construction method

​ Create a parameterized construct

public class UserServiceImpl implements UserService {
@Override
public void save() {
ApplicationContext applicationContext = new 
                 ClassPathXmlApplicationContext("applicationContext.xml");       UserDao userDao = (UserDao) applicationContext.getBean("userDao");    
          userDao.save();
    }
 }

​ Configure the Spring container to inject when the parameterized construction is called

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">                <constructor-arg ></constructor-arg>
</bean>

②set method

​ Add setUserDao method in UserServiceImpl

public  class  UserServiceImpl  implements  UserService  {
     private UserDao userDao;
    public  void  setUserDao (UserDao userDao)  {
         this .userDao = userDao;  
        } 
    @Override    
    public void save() {      
         userDao.save();
    }
}

​ Configure the Spring container to call the set method for injection

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
    <property />
</bean>

set method: P namespace injection

The essence of P namespace injection is also set method injection, but it is more convenient than the above set method injection, which is mainly reflected in the configuration file, as follows:

​ First, you need to introduce the P namespace:

xmlns:p="http://www.springframework.org/schema/p"

Second, the injection method needs to be modified

<bean id="userService" class="com.itheima.service.impl.UserServiceImpl" p:userDao-
 ref="userDao"/>

3.8 Data Types of Bean Dependency Injection

The above operations are all injected reference beans. The reference of the object can be injected. Common data types, collections, etc. can be injected in the container.

Three data types for injecting data

common data type

reference data type

Collection data type

The reference data type will not be repeated here. The previous operations are all injected into the reference of the UserDao object. The following will take the injection of the set method as an example to demonstrate the injection of common data types and collection data types.

Data types for dependency injection of beans

(1) Injection of common data types

public class UserDaoImpl implements UserDao {
private String company;
    private int age;
    public void setCompany(String company) {
        this.company = company;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void save() {
        System.out.println(company+"==="+age);
        System.out.println("UserDao save method running....");   
    }
}

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property ></property>
    <property ></property>
</bean>

(2) Injection of collection data type (List)

public class UserDaoImpl implements UserDao {
    private List<String> strList;
    public void setStrList(List<String> strList) {
        this.strList = strList;
    }
    public void save() {
        System.out.println(strList);
        System.out.println("UserDao save method running....");
    }
}

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property >
        <list>
            <value>aaa</value>
            <value>bbb</value>
            <value>ccc</value>
        </list>
    </property>
</bean>

(3) Injection of collection data type (List)

public class UserDaoImpl implements UserDao {
    private List<User> userList;
    public void setUserList(List<User> userList) {
    this.userList = userList;  
 }
public void save() {
    System.out.println(userList);
    System.out.println("UserDao save method running....");
    }
}

<bean id="u1" class="com.itheima.domain.User"/>
<bean id="u2" class="com.itheima.domain.User"/>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property >
        <list>
            <bean class="com.itheima.domain.User"/>
            <bean class="com.itheima.domain.User"/>
            <ref bean="u1"/>
            <ref bean="u2"/>       
        </list>
    </property>
</bean>

(4) Injection of collection data type ( Map )

public class UserDaoImpl implements UserDao {
    private Map<String,User> userMap;
    public void setUserMap(Map<String, User> userMap) {
    this.userMap = userMap;
    }    
public void save() {      
    System.out.println(userMap);
    System.out.println("UserDao save method running....");
    }
}

<bean id="u1" class="com.itheima.domain.User"/>
<bean id="u2" class="com.itheima.domain.User"/>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property >
        <map>            
            <entry key="user1" value-ref="u1"/>
            <entry key="user2" value-ref="u2"/>
        </map>
    </property>
</bean>

(5) Injection of collection data type (Properties)

public class UserDaoImpl implements UserDao {
    private Properties properties;
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
    public void save() {
        System.out.println(properties);
        System.out.println("UserDao save method running....");
    }
}

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property >
        <props>
            <prop key="p1">aaa</prop>
            <prop key="p2">bbb</prop> 
            <prop key="p3">ccc</prop>
        </props>
    </property>
</bean>

3.9 Introducing other configuration files (development by modules)

In actual development, Spring has a lot of configuration content, which makes Spring configuration very complicated and bulky. Therefore, part of the configuration can be disassembled into other configuration files, and the Spring main configuration file is loaded through the import tag.

<import resource="applicationContext-xxx.xml"/>

4. Spring related API

4.1 Inheritance system of ApplicationContext

applicationContext: interface type, representing the application context, through which the Bean object in the Spring container can be obtained

4.2 Implementation class of ApplicationContext

1)ClassPathXmlApplicationContext

​ It is to load the configuration file from the root path of the class. It is recommended to use this

2)FileSystemXmlApplicationContext

​ It loads the configuration file from the disk path, and the configuration file can be anywhere on the disk.

3)AnnotationConfigApplicationContext

When using annotations to configure container objects, you need to use this class to create a spring container. It is used to read annotations.

4.3 use of getBean() method

public Object getBean(String name) throws BeansException {  
    assertBeanFactoryActive();   
    return getBeanFactory().getBean(name);
}
public <T> T getBean(Class<T> requiredType) throws BeansException {                     assertBeanFactoryActive();
    return getBeanFactory().getBean(requiredType);
}

Among them, when the data type of the parameter is a string, it means that the Bean instance is obtained from the container according to the bean’s id, and the return is Object, which needs to be converted.

When the data type of the parameter is Class type, it means that the bean instance is matched from the container according to the type. When there are multiple beans of the same type in the container, this method will report an error

The getBean() method is used

ApplicationContext applicationContext = new 
            ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");
  UserService userService2 = applicationContext.getBean(UserService.class);




    assertBeanFactoryActive();
    return getBeanFactory().getBean(requiredType);
}

Among them, when the data type of the parameter is a string, it means that the Bean instance is obtained from the container according to the id of the bean, and the return is Object, which needs to be forced.

When the data type of the parameter is Class type, it means that the bean instance is matched from the container according to the type. When there are multiple beans of the same type in the container, this method will report an error

The getBean() method is used

ApplicationContext applicationContext = new 
            ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");
  UserService userService2 = applicationContext.getBean(UserService.class);

Leave a Comment

Your email address will not be published. Required fields are marked *