1. spring overview
1.1 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 spring MVC, 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
1.2 development history of spring
Rod Johnson (father of Spring)
2017
The latest version of Spring, Spring 5.0, was released in September 0
General Edition (GA)
1.3 advantages of spring
Convenient decoupling and simplified development
AOP programming support
Declarative transaction support
Facilitate program testing
Spring architecture
2. spring quick start
2.1 Spring program development steps
2.1.1 import the coordinates of the basic package developed by Spring
<properties> <spring.version>5.0.5.RELEASE</spring.version> </properties> <!--Import spring of context Coordinates, context rely on core,beans,expression--> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
2.1.2 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.1.3 create Spring core configuration file
① Create ApplicationContext under the classpath (resources) XML 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"> </beans>
2.1.4 configure UserDaoImpl in 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.fanyi.dao.impl.UserDaoImpl"></bean> </beans>
2.1.5 obtain 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 basic configuration of bean tag
① 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.
3.1.1 basic attributes:
attribute | introduce |
---|---|
id | The unique identification of the Bean instance in the Spring container |
class | The fully qualified name of the Bean |
scope | Specifies the scope of the object |
3.2 Bean tag range configuration
3.2.1 scope: refers to the scope of the object. The values are as follows:
Value range | explain |
---|---|
singleton | Default, singleton |
prototype | Multiple cases |
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 into the session domain |
global session | In the WEB project, the application is in the Portlet environment. If there is no Portlet environment, the global session is equivalent to the session |
3.2.2 scope values are singleton and prototype
\ | singleton | prototype |
---|---|---|
Number of instantiations of Bean | One | Multiple |
Bean instantiation timing | When the Spring core file is loaded | When the getBean() method is called |
Bean life cycle 👇 | ⬇ | ⬇ |
objects creating | When the application loads and creates a container, the object is created | When using an object, create a new object instance |
Object run | As long as the container is, the object remains alive | As long as the object is in use, it remains alive |
Object destruction | When the application unloads and destroys the container, the object is destroyed | When the object is not used for a long time, it is recycled by the Java garbage collector |
3.3 Bean lifecycle configuration
attribute | introduce |
---|---|
init-method | Specifies the name of the initialization method in the class |
destroy-method | Specifies the name of the destroy method in the class |
3.4 three methods of bean instantiation
3.4.1 instantiation using parameterless construction method
① it will create class objects according to the default parameterless construction method. If there is no default parameterless constructor in the bean, the creation will fail
<bean id="userDao" class="com.fanyi.dao.impl.UserDaoImpl"/>
3.4.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.fanyi.factory.StaticFactoryBean" factory-method="createUserDao" />
3.4.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.fanyi.factory.DynamicFactoryBean"/> <bean id="userDao" factory-bean="factoryBean" factory-method="createUserDao"/>
3.5 introduction to bean dependency injection
① 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(); } }
② Give Spring the right to create UserServiceImpl
<bean id="userService" class="com.fanyi.service.impl.UserServiceImpl"/>
③ Obtain UserService from Spring container for operation
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.save();
3.6 dependency injection concept of bean
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 will not eliminate them. For example, the business layer will still call the methods of the persistence layer. |
After using Spring, the dependency between the business layer and the persistence layer can be maintained by Spring. |
Simply put, it means waiting for the framework to transfer the persistence layer object to the business layer without getting it ourselves |
3.7 dependency injection method of bean
3.7.1 construction method
① 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="com.fanyi.dao.impl.UserDaoImpl"/> <bean id="userService" class="com.fanyi.service.impl.UserServiceImpl"> <constructor-arg name="userDao" ref="userDao"></constructor-arg> </bean>
3.7.2 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 and call the set method for injection
<bean id="userDao" class="com.fanyi.dao.impl.UserDaoImpl"/> <bean id="userService" class="com.fanyi.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> </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"
Secondly, the injection method needs to be modified
<bean id="userService" class="com.fanyi.service.impl.UserServiceImpl" p:userDao- ref="userDao"/>
3.8 data types of bean dependency injection
The above operations are all injected reference beans. The references of processed objects can be injected. Ordinary data types and collections can be injected in the container.
Three data types of injected data |
---|
Common data type |
Reference data type |
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.
3.8.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.fanyi.dao.impl.UserDaoImpl"> <property name="company" value="Intelligence Podcast"></property> <property name="age" value="15"></property> </bean>
3.8.2 injection of set 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.fanyi.dao.impl.UserDaoImpl"> <property name="strList"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> </bean>
3.8.3 injection of set 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.fanyi.domain.User"/> <bean id="u2" class="com.fanyi.domain.User"/> <bean id="userDao" class="com.fanyi.dao.impl.UserDaoImpl"> <property name="userList"> <list> <bean class="com.fanyi.domain.User"/> <bean class="com.fanyi.domain.User"/> <ref bean="u1"/> <ref bean="u2"/> </list> </property> </bean>
3.8.4 injection of set data type (map < string, user >)
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.fanyi.domain.User"/> <bean id="u2" class="com.fanyi.domain.User"/> <bean id="userDao" class="com.fanyi.dao.impl.UserDaoImpl"> <property name="userMap"> <map> <entry key="user1" value-ref="u1"/> <entry key="user2" value-ref="u2"/> </map> </property> </bean>
Injection of collection data types (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.fanyi.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)
In the actual development, there are a lot of configuration contents in Spring, which leads to the complexity and large volume of Spring configuration. Therefore, some configurations can be disassembled into other configuration files, and loaded in the main Spring configuration file through the import tag
<import resource="applicationContext-xxx.xml"/>
4. spring related API s
4.1 inheritance system of ApplicationContext
applicationContext: interface type, which represents the application context. Bean objects in the Spring container can be obtained through its instance
4.2 implementation class of ApplicationContext
① ClassPathXmlApplicationContext
It loads the configuration file from the root path of the class. This is recommended
② FileSystemXmlApplicationContext
It loads the configuration file from the disk path. The configuration file can be anywhere on the disk.
③ AnnotationConfigApplicationContext
When configuring container objects with annotations, 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); }
Where, 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 id, and the return is Object, which needs to be forced.
When the data type of the parameter is Class type, it means that Bean instances are 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 uses
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService1 = (UserService) applicationContext.getBean("userService"); UserService userService2 = applicationContext.getBean(UserService.class);