Spring_IoC&DI

Spring_IoC&DI


1. spring Overview

1.1 Spring is what (understanding)

Spring is a layered Java SE / EE lightweight open source application framework for full-stack to IoC (Inverse Of Control: inversion control) and AOP (Aspect Oriented Programming: Oriented Programming) kernel.

SpringMVC provides the presentation layer and persistence layer Spring JDBCTemplate and business layer transaction management and other enterprise applications technology, but also the integration of the open source world many well-known third-party frameworks and libraries, has become the largest enterprise applications using Java EE open source framework

1.2 Spring development (understanding)

Rod Johnson (Spring father)

September 2017 Spring released the latest version of Spring5.0 generic version (GA)

1.3 Spring advantage (understanding)

Convenient decoupling, simplify development

AOP programming support

Support for declarative transactions

To facilitate the testing program

1.4 Spring architecture (understand)

2. spring Quick Start

2.1 Spring program development steps

① packet into the base coordinate Spring Development

② write Dao interface and implementation class

③ create Spring core profile

④ configuration UserDaoImpl in the Spring configuration file

⑤ use the API to obtain the Bean instance Spring

Spring basic package developed by introducing the coordinates 2.2

<properties>
    <spring.version>5.0.5.RELEASE</spring.version>
</properties>
<!--导入spring的context坐标,context依赖core、beans、expression-->
<dependencies> 
    <dependency>  
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>${spring.version}</version>
    </dependency>
</dependencies>

Write Dao 2.3 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....");
    }
}

Creating Spring 2.4 core profile

ApplicationContext.xml create profiles in 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 Configuring 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>    
    //bean标签:在Spring的容器中 声明一个Bean对象
    //id属性:为bean类的唯一标识,不可重复
    //class属性:创建的bean全类名

</beans>

2.6 is obtained using an API Bean instance Spring

@Test
public void test1(){

        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) app.getBean("userDao");                  
        userDao.save();
 }

3. Spring configuration file

3.1 Bean basic configuration label

Spring used to configure the objects handed over to create.

By default, it is called the class constructor without parameters, if there is no no-argument constructor can not be created.

The basic attributes:

id: Bean instance uniquely identifies Spring container

class: Bean fully qualified name

3.2 Bean label range configuration

scope: refers to a subject's scope, the following values:

Ranges Explanation
singleton Default single embodiment (common)
prototype Multi-example manner
request WEB project, Spring Bean's create an object, the object will be credited to request the domain
session WEB project, Spring Bean's create an object, the object will be credited to the session domain
global session WEB project, the application environment in the Portlet, Portlet environment so if there is no equivalent session globalSession

1) When the value of a singleton scope

Bean instantiation Number: 1

Bean instantiation timing: When Spring core file is loaded, instantiated Bean instance configuration

Bean's life cycle:

Object creation: When the application is loaded, create a container object is created

Object run: as long as the container, the object has been alive

Object Destruction: When uninstalling the application, when the destruction of container, the object is destroyed

2) When the value is prototype scope

Bean instantiation Number: a plurality of

Bean instantiation timing: When you call getBean () method instantiates Bean

Object creation: When using the object, creating a new object instance

Object run: as long as the object is in use, has been alive

Object is destroyed: when the object is not a long time, the Java garbage collector recovered

3.3 Bean Life Cycle Configuration

init-method: Specifies the name of the class initialization method

destroy-method: Specifies the name of the class methods of destruction

3.4 Bean instantiated in three ways

1) using the constructor with no arguments instantiated

It will create a class object with a default constructor with no arguments, if the bean does not default no-argument constructor will be created fail

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

2) static factory method to instantiate
    to create a factory class (StaticFactoryBean), the method comprising a static factory class and returns the object (createUserDao)
static method returns Bean instance factory

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

In ApplicationContext.xml profile, static factory class attribute declaration full class name of the class, and adds factory-method attribute, method name attribute value of the static factory class
when Spring reads the configuration file, based on factory-method attribute , call the static method to return the object UserDaoImpl

<bean id="userDao" class="com.itheima.factory.StaticFactoryBean" factory-method="createUserDao" />
    //等价于:UserDao userDao = StaticFactoryBean.createUserDao();

3) Examples of the method to instantiate the factory
    to create a factory class (DynamicFactoryBean), non-static and returns in the factory class object's method (createUserDao)
non-static method returns Bean instance factory

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

    When the method is non-static factory class, then it can not be called directly, you need to let the Spring container to create an object factory class,
then by factory-bean, factory-method attribute to return

<bean id="factoryBean" class="com.itheima.factory.DynamicFactoryBean"/>
    //等价于:factoryBean = new DynamicFactoryBean;
<bean id="userDao" factory-bean="factoryBean" factory-method="createUserDao"/>
    //等价于:UserDao userDao = factoryBean.createUserDao();


3.5 Bean dependency injection entry

① create UserService, UserService internal calling UserDao the save () method

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

② creates a right handed UserServiceImpl Spring

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

③ obtained UserService Spring operated from the vessel

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

3.6 Bean concept of dependency injection

Dependency injection (Dependency Injection): it is embodied in the Spring Framework core IOC.

When programming, through inversion of control, the creation of objects handed over to Spring, but the code does not depend on the situation impossible.

IOC decoupling only reduce their dependency, but not eliminated. For example: the business layer will call the method persistence layer.

This dependency that the business layer and persistence layer, after using Spring, Spring to let maintained.

Simply put, it is to wait for the incoming object persistence layer framework to the business layer, instead of our own to get

3.7 Bean's dependency injection

① constructor

Have created a reference configuration

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

Implanting Spring container configuration parameters configured with a call

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

②set method

Add setUserDao method in the UserServiceImpl

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

Spring container configuration method call set injection

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

Method set: P injection namespace

P namespace is essentially set injection injection method, but compared to the above-described method of injection is more convenient to set, mainly in the configuration file as follows:

First, we need to introduce P namespace:

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

Secondly, the need to modify the injection method

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

Injection of 3.8 Bean dependency data type

The above operations are injected references Bean, the reference object may be injected, a common data type, and so can be injected in the collection vessel.

Injected three data types of data

Common data types

Reference data types

Collection data types

Wherein reference data types, will not repeat herein, is a reference to the previous operation of implanting UserDao object, the following method of injection will be set as an example, a set of presentation data and common data type injection type.

Bean data dependency injection type

(1) a common data type injection

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 name="company" value="传智播客"></property>
    <property name="age" value="15"></property>
</bean>

(2) aggregate data type (List ) Injection

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 name="strList">
        <list>
            <value>aaa</value>
            <value>bbb</value>
            <value>ccc</value>
        </list>
    </property>
</bean>

(3) Data collection type (List ) Injection

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 name="userList">
        <list>
            <bean class="com.itheima.domain.User"/>
            <bean class="com.itheima.domain.User"/>
            <ref bean="u1"/>
            <ref bean="u2"/>       
        </list>
    </property>
</bean>

(4) a set of data types (Map <String, User>) injection

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 name="userMap">
        <map>            
            <entry key="user1" value-ref="u1"/>
            <entry key="user2" value-ref="u2"/>
        </map>
    </property>
</bean>

(5) a set of data types (Properties) injection

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 name="properties">
        <props>
            <prop key="p1">aaa</prop>
            <prop key="p2">bbb</prop> 
            <prop key="p3">ccc</prop>
        </props>
    </property>
</bean>

3.9 introduction of other configuration files (sub-module development)

The actual development, Spring configuration content very much, which leads to Spring configuration is very complicated and large volume, so that part of the configuration can be disassembled to other profiles, and loaded through the main import label in the Spring configuration file

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

4. spring relevant API

4.1 ApplicationContext inheritance system

applicationContext: Interface Type, represents the application context, the object can be obtained Bean Spring container by examples

4.2 ApplicationContext implementation class

1)ClassPathXmlApplicationContext

It is to load the configuration file from the root class is recommended that

2)FileSystemXmlApplicationContext

It is to load the configuration file from the disk path, the configuration file can be used anywhere in the disk.

3)AnnotationConfigApplicationContext

When using annotations Configuration container object, you need to use this class to create a spring container. It is used to read notes.

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

Wherein, when the data type of the parameter is a string that represents the vessel is obtained in accordance with Example Bean Bean's id, returns yes Object, turn require strong.

When the data type parameter is Class type, which matches Bean instance according to the type of the container, when the container has a plurality of the same type when Bean, this method will be given

the getBean () method

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

Guess you like

Origin www.cnblogs.com/lichusan/p/12181212.html