catalogue
3.1. Create a java project and import the corresponding jar package
3.2. Create configuration file
3.3. Add corresponding modules
3.4. Hand over bean instantiation to Spring
4. Injection by construction method
5. General attribute injection
1. What is spring
Spring is an open source framework. Spring is a lightweight Java development framework rising in 2003. It is derived from some concepts and prototypes described by Rod Johnson in his book expert one on one J2EE development and design.
It is created to solve the complexity of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows users to choose which component to use, and provides an integrated framework for J2EE application development. Spring uses basic JavaBean s to do things that previously could only be done by EJB s. However, the use of spring is not limited to server-side development. From the perspective of simplicity, testability and loose coupling, any Java application can benefit from spring. The core of spring is inversion of control (IOC) and aspect oriented (AOP). In short, spring is a layered lightweight open source framework.
IOC : Talking about IOC -- what is IOC_ Zhe CSDN blog_ ioc
Six principles of software design: Six principles of design mode
Low coupling: Understanding of low coupling_ Ellis 1970 blog - CSDN blog_ Low coupling
2. Why use Spring?
- Convenient decoupling and simplified development
- Spring is a big factory, which can manage all object creation and dependency maintenance
- With the support of AOP programming, Spring provides aspect oriented programming, which can easily realize the functions of permission interception, operation monitoring and so on
- Declarative transaction support can complete transaction management only through configuration,
- Without manual programming, Spring supports Junit4 and can easily test Spring programs through annotations
- It is convenient to integrate various excellent frameworks. Spring does not exclude various excellent open source frameworks. It internally provides direct support for various excellent frameworks (such as Struts, Hibernate, MyBatis, Quartz, etc.)
- Reduce the difficulty of using Java EE APIs. Spring provides encapsulation for some APIs that are very difficult to use in Java EE development (JDBC, JavaMail, remote call, etc.), which greatly reduces the difficulty of applying these APIs
3. Environmental construction
3.1. Create a java project and import the corresponding jar package
3.2. Create configuration file
The name of the configuration file can be set arbitrarily. It is recommended to set it to ApplicationContext XML, so here we create an application context 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>
3.3. Add corresponding modules
Add dao, model and service layer code in the project
3.4. Hand over bean instantiation to Spring
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl" /> <!--name Attribute name/ref Referenced bean Name of--> <bean id="userService" class="com.tledu.service.UserService"> <property name="userDao" ref="userDao" /> </bean>
3.5 testing
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserServiceImpl userServiceImpl = context.getBean("userService", UserServiceImpl.class); User user = userServiceImpl.getUserById(1); System.out.println(user); }
4. Injection by construction method
As can be seen from the above program, the object is injected through the set method, so how to inject through the construction method?
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl" /> <bean id="userService" class="com.tledu.service.UserService"> <constructor-arg ref="userDao"/> </bean>
5. General attribute injection
What we injected above is related objects. For example, how to inject the value of int
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl"> <!-- If not pointing to an object,Direct use value Just set the value --> <property name="daoId" value="82"></property> <property name="daoStatus" value="good"></property> </bean>
6,scope
scope is a very key concept in spring. In short, it is the life cycle of objects in the spring container (IOC container), which can also be understood as the creation method of objects in the spring container.
At present, there are five values for scope:
Before Spring 2.0, there were singleton and prototype;
After Spring 2.0, in order to support the ApplicationContext of web applications, three other types are enhanced: request, session and global session. They are only implemented in web applications, usually used together with XmlWebApplicationContext
6.1,singleton
This value indicates that there is only one instance when it is created in the container, and all references to this bean are single instances.
That is, the creation object is in singleton mode, and if it is not set, it is singleton by default
6.2,prototype
When the spring container outputs the bean object of prototype, it will regenerate a new object to the requester every time. Although the instantiation and property setting of this type of object are the responsibility of the container, as long as the preparation is completed and the object instance is returned to the requester, the container will no longer have the reference of the current object, The requester needs to be responsible for the management of the subsequent life cycle of the current object, including the destruction of the object. In other words, every time the container returns a new instance of the object to the requester, the object "lives and dies by itself". The most typical embodiment is to change the scope of action to prototype when integrating spring and struts 2.
Simply put, a new object is created every time it is acquired, and the life cycle of this object is not managed by Spring
6.3,request
The request, session, and global session types are only applicable to web applications and are usually used with XmlWebApplicationContext.
<bean id ="requestPrecessor" class="...RequestPrecessor" scope="request" />
The Spring container, XmlWebApplicationContext, will create a new requestpreprocessor object for each HTTP request. When the request ends, the life cycle of the object will end, just like the life cycle of request in java web. When 100 HTTP requests come in at the same time, the container will create 10 new requestpreprocessor instances for these 10 requests, and they do not interfere with each other. In short, request can be regarded as a special case of prototype. Except that the scenario is more specific, it is similar in semantics.
6.4,session
For web applications, the most common information put into a session is the user's login information. For this information put into a session, we can use the following form to formulate the scope as a session:
<bean id ="userPreferences" class="...UserPreferences" scope="session" />
The Spring container will create its own new UserPreferences instance for each independent session, which will survive longer than the bean of the request scope. There is no difference in other aspects, such as the life cycle of the session in the java web.
6.5,global session
<bean id ="userPreferences" class="...UserPreferences" scope="globalsession" />
Global session is meaningful only when it is applied in the web application based on porlet. It maps to the global session of porlet. If this scope is used in the web application of ordinary servlet, the container will treat it as the scope of ordinary session
6.6. Configure scope mode
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl"> <!-- If not pointing to an object,Direct use value Just set the value --> <property name="daoId" value="82"></property> <property name="daoStatus" value="good"></property> </bean > <!-- scope singleton : Only one single instance is created,Default is prototype : every time getBean Will create a new instantiated object request,session : Special environment support required --> <bean id="userService" class="com.tledu.service.UserService" scope="singleton"> <!-- Construction method injection --> <constructor-arg> <ref bean="userDao" /> </constructor-arg> </bean>
7. Collection properties
7.1 related categories
The corresponding variable is provided in UserDaoImpl
private List<String> lists; private Set<String> sets; private Map<String, String> maps; public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public Set<String> getSets() { return sets; } public void setSets(Set<String> sets) { this.sets = sets; } public Map<String, String> getMaps() { return maps; } public void setMaps(Map<String, String> maps) { this.maps = maps; }
7.2 configuration file
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl"> <property name="lists" > <list> <value>1</value> <value>2</value> </list> </property> <property name="sets" > <!-- set Non repeatable,Repeat without adding,So there's only the first three --> <set> <value>3</value> <value>3</value> <value>5</value> <value>4</value> </set> </property> <property name="maps"> <!-- mapkey Non repeatable,repeat key Do not add,value cover --> <map> <entry key="1" value="2"></entry> <entry key="1" value="3"></entry> <entry key="2" value="2"></entry> </map> </property> </bean> <bean id="userService" class="com.tledu.zrz.service.UserService" scope="singleton"> <!-- Construction method injection --> <constructor-arg> <ref bean="userDao" /> </constructor-arg> </bean>
7.3 testing
8. Automatic assembly
There are two ways to inject objects
1 set method injection
2 construction method injection
Now let's learn about automatic injection, that is, there is no need to specify the above two methods
Autowire: automatic assembly, two values
1 byName
2 byType
8.1,byName
byName matches the name of the setter method. If it cannot be found, it will not be assigned
For example, the setUserDao method {will find UserDao. If the bean ID is UserDao, it can't be found. It's case sensitive
Setting mode
autowire="byName">
8.2,byType
byType is matched according to the data type in the parameter list of the setter method, if beans If multiple objects of the same type appear in XML, an error will be reported
For example, the setUserDao(UserDao userDao) method {will find UserDao. If it is an interface, it will find the corresponding implementation class object
Setting mode
autowire="byType">
Note: the use of automatic assembly requires a public parameterless construction. Although the object can still be created even if it is a private construction method, it is better to provide a public one in case other frameworks need it
8.3,constructor
Dependency injection can be performed according to the constructor.
9. Lifecycle and late loading
Previous servlet life cycle
Construction method -- init -- service -- destroy
What about the life cycle of spring created objects?
There are no init, service and destroy in Spring, but we can specify a method to execute after the object is created and a method to execute when it is finally destroyed
9.1 life cycle
9.1. 1. Related classes
The corresponding method is provided in UserService
public void init(){ System.out.println("init--------"); } public void destroy(){ System.out.println("destroy----------"); } public UserService() { System.out.println("service Construction method"); }
9.1. 2. Configuration file
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl" > </bean> <!-- init-method : Method for setting initialization destory-method : Used to set the method for destroying resources --> <bean id="userService" class="com.tledu.service.UserService" autowire="byName" init-method="init" destroy-method="destroy" > </bean>
9.1. 3. Testing
@Test public void testAdd() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "beans.xml"); // userService is the id or name of the bean UserService userService = (UserService) applicationContext .getBean("userService"); // // userService.add(null); System.out.println(userService.getUserDao()); // Destroy the Spring container applicationContext.destroy(); }
Destroy executes because we create objects in singleton mode by default
At this time, the object life cycle will be bound with the Spring container life cycle, so when we destroy the Spring container, we will destroy all objects and automatically call the destroy method
However, if we set the scope to prototype, the life cycle of the object will not be bound to the Spring container, and the destroy method of the object will not be executed when the Spring container is destroyed
such as
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl" > </bean> <!-- init-method : Method for setting initialization destory-method : Used to set the method for destroying resources --> <bean id="userService" class="com.tledu.zrz.service.UserService" scope="prototype" autowire="byName" init-method="init" destroy-method="destroy" > </bean>
9.2 late loading
The Spring container is executing by default
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
When parsing, create an object and call init,
If we don't want a class to create an object when it is parsed, but when it is used, we need to set the late load. For example, we can set the late load of userService
9.2. 1. Related classes
Add an output statement to the constructor in UserDaoImpl and UserService for testing
public UserDaoImpl(){ System.out.println("Dao Construction method"); } public UserService() { System.out.println("service Construction method"); }
9.2. 2. Configuration file
<bean name="userDao" class="com.tledu.dao.impl.UserDaoImpl" > <bean id="userService" class="com.tledu.service.UserService" scope="prototype" autowire="byName" init-method="init" destroy-method="destroy" lazy-init="true" > </bean>
9.2. 3. Testing
@Test public void testAdd() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "beans.xml"); }
result
It can be seen from the results that the UserService object is not created, so when is it created?
UserService userService = (UserService) applicationContext.getBean("userService");
Created when getBean() is called
Or when this object is used, for example, we get the userservice object, but we need to inject the userDao object into the userservice. At this time, even if we use getBean("userDao") instead of getBean("userservice"), the userDao object will be created, because userDao is used in the userservice
For ease of use, Spring also proposes default lazy init = "true"
For example, if we create 10 objects through xml, and these 10 objects need to be loaded late, it is troublesome to set lazr init in each bean tag
So we can add default lazy init = "true" in the beans tag to load all beans late
Default lazy init and lazy init can exist at the same time. For example, if only one of the 10 objects does not need to be loaded late, you can use default lazy init = true to set all late loads, and then add lazy init = false to the specified bean
<?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" default-lazy-init="true" >