IoC and DI of Spring

Introduction to Spring

What is Spring

Spring is a lightweight open source framework for layered Java SE/EE application full stack, with IoC (Inverse Of Control) and AOP (Aspect Oriented Programming) as the kernel.

It provides many enterprise application technologies such as presentation layer SpringMVC, persistence layer spring JDBC template and business layer transaction management. It can also integrate many famous third-party frameworks and class libraries in the world, and gradually become the most used open source framework for Java EE enterprise applications.

Development history of spring

In 1997, IBM put forward the idea of EJB
In 1998, SUN formulated the development standard specification EJB1.0
In 1999, EJB 1.1 was released
In 2001, EJB 2.0 was released
In 2003, EJB2.1 was released
In 2006, EJB 3.0 was released

Rod Johnson (father of Spring)
Expert One-to-One J2EE Design and Development(2002)
This paper expounds the advantages and solutions of J2EE development and design using EJB
Expert One-to-One J2EE Development without EJB(2004)
This paper expounds the solution of J2EE development without EJB (Spring prototype)

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

Advantages of Spring

1) Convenient decoupling and simplified development
Through the IoC container provided by Spring, the dependencies between objects can be controlled by Spring to avoid excessive coupling caused by hard coding.
Users do not have to write code for the very low-level requirements such as singleton pattern class and attribute file parsing, and can focus more on the upper-level applications.

2) AOP programming support
Through the AOP function of Spring, it is convenient for aspect oriented programming. Many functions that are not easy to be realized with traditional OOP can be easily realized through AOP.

3) Declarative transaction support
It can free us from the monotonous and boring transaction management code, and carry out transaction management flexibly in a declarative way, so as to improve the development efficiency and quality.

4) Facilitate program testing
Almost all testing work can be carried out in a container independent programming way. Testing is no longer an expensive operation, but a thing to do at will.

5) Convenient integration of various excellent frameworks
Spring supports various excellent frameworks (Struts, Hibernate, Hessian, Quartz, etc.).

6) Reduce the difficulty of using Java EE API
Spring has a thin encapsulation layer for Java EE APIs (such as JDBC, JavaMail, remote call, etc.), which greatly reduces the difficulty of using these APIs.

7) Java source code is a classic learning example
Spring's source code design is exquisite, its structure is clear, and its ingenuity is unique. It everywhere reflects the master's flexible use of Java design patterns and his profound understanding of Java technology
Attainments. Its source code is not intended to be an example of best practices in Java technology.

Spring architecture

Spring quick start

Spring program development steps:


technological process:
1. Import the coordinates of the basic package developed by Spring
2. Write Dao interface and implementation class
3. Create Spring core configuration file
4. Configure UserDaoImpl in the Spring configuration file
5. Use Spring's API to get Bean instances

Import the coordinates of the basic package developed by Spring

<properties>  
	<spring.version>5.0.5.RELEASE</spring.version>
</properties>

<dependencies>  
<!--Import spring of context Coordinates, context rely on core,beans,expression-->  			  
	<dependency>    
		<groupId>org.springframework</groupId>    
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>  
	</dependency>
</dependencies>

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

Create 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"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>

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"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
       
		<bean id="userDao" class="java.dao.impl.UserDaoImpl"></bean>

</beans>

Active Bean instances using Spring's API

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

Summary: Spring development steps
1. Import coordinates
2. Create Bean
3. Create applicationContext.xml
4. Configure in configuration file
5. Create ApplicationContext object getBean

Spring configuration file:

Bean tag configuration

The configuration object is created by Spring.
By default, it calls the parameterless constructor in the class. If there is no parameterless 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

Scope of scope object:

Bean tag range configuration

1) When the value of scope is singleton
Number of instantiations of Bean: 1
Bean instantiation timing: instantiate the configured bean instance when the Spring core file is loaded
Bean lifecycle:
Object creation: when the application loads and creates a container, the object is created
Object running: the object remains alive as long as the container is
Object destruction: when the application unloads and destroys the container, the object is destroyed
2) When the value of scope is prototype
Number of Bean instantiations: multiple
Instantiation timing of Bean: instantiate Bean when calling getBean() method
Object creation: creates a new object instance when using an object
Object running: as long as the object is in use, it will always be alive
Object destruction: when an object is not used for a long time, it is recycled by the Java garbage collector

Bean tag lifecycle configuration

Init method: Specifies the name of the initialization method in the class
Destroy method: Specifies the name of the destroy method in the class

Three methods of Bean instantiation

Parameterless construction method instantiation
Factory static method instantiation
Factory instance method instantiation

1) Instantiate using the parameterless construction method
It will create class objects according to the default parameterless constructor. If there is no default parameterless constructor in the bean, the creation will fail

<bean id="userDao" class="java.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="java.factory.StaticFactoryBean" factory-method="createUserDao" />

3) Factory instance method instantiation
The non static method of the factory returns a Bean instance

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

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

Introduction to Bean dependency injection

1. Create UserService. UserService calls the save() method of UserDao internally

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

2. Give Spring the right to create UserServiceImpl

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

3. Obtain UserService from Spring container for operation

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

Dependency injection analysis of Bean

At present, both UserService instances and UserDao instances exist in the Spring container. The current practice is to obtain UserService instances and UserDao instances outside the container, and then combine them in the program.

Because both UserService and UserDao are in the Spring container, and the final program directly uses UserService, you can set UserDao inside UserService in the Spring container.

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

When writing the program, the creation of objects is handed over to Spring through control inversion, but there can be no dependency in the code.
IOC decoupling only reduces their dependencies, but it will not eliminate them. For example, the business layer will still call the methods of the persistence layer.

After using Spring, Spring can maintain the dependency between the business layer and the persistence layer.
Simply put, it means waiting for the framework to transfer the persistence layer object to the business layer without getting it ourselves.

How to inject UserDao into UserService?

1. Construction method
2. set method

1) set method injection
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="java.dao.impl.UserDaoImpl"/>
<bean id="userService" class="java.service.impl.UserServiceImpl">    
	<property name="userDao" ref="userDao"/>
</bean>

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"

Secondly, the injection method needs to be modified

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

2) Construction method injection
Create parametric structure

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 calling parameterized constructs

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

Data type of Bean dependency injection

The above operations are all injected reference beans. References to processed objects can be injected. Ordinary data types and collections can be injected in containers.

Three data types of injected data
1. Common data type
2. Reference data type
3. Collection data type

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

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="java.dao.impl.UserDaoImpl">    
	<property name="company" value="csdn"></property>   
  <property name="age" value="15"></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="java.dao.impl.UserDaoImpl">    
	<property name="strList">        
		<list>            
			<value>aaa</value>            
			<value>bbb</value>            
			<value>ccc</value>        
		</list>    
	</property>
</bean>

Injection of collection data type (List)

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

Key spring configurations:

<bean>label
    id attribute:In container Bean Unique ID of the instance. Duplicate is not allowed
    class attribute:To instantiate Bean Fully qualified name of
    scope attribute:Bean The scope of action is Singleton(default)and prototype
    <property>Labels: attribute injection
        name Attribute: attribute name
        value Attributes: injected normal attribute values
        ref Properties: injected object reference values
        <list>label
        <map>label
        <properties>label
    <constructor-arg>label
<import>label:Import other Spring Sub document of

Tags: Java Spring

Posted on Fri, 26 Nov 2021 08:24:04 -0500 by Encrypt