Configuring Spring in the Web project
To configure spring in a Web project, you first need to add the Spring-web package to the project, and I'm using Maven's Web project, which relies on the Pom.xml configuration file configuration as follows:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.14.RELEASE</version> < /dependency> <dependency> <groupId>org.springframework</groupId> <art Ifactid>spring-web</artifactid> <version>4.3.14.RELEASE</version> </DEPENDENCY&G T <dependency> <groupId>javax</groupId> <artifactid>javaee-api</artifactid& Gt <version>7.0</version> <scope>provided</scope> </dependency> <de Pendency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.0</version> <scope>test</scope> </dependency> <dEpendency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupid>m Ysql</groupid> <artifactId>mysql-connector-java</artifactId> <version>5.1.44 </version> </dependency> </dependencies>
The spring listener is then configured in the project's Web. xml file, and the Web. XML content is as follows:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 配置Spring的监听器类 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置Spring配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:app.xml</param-value> </context-param></web-app>
Here's the configuration to illustrate, when you configure the path of the spring configuration file, if your profile is placed under Web-inf does not need to add Classpath: prefix, only need to write the path, for example:
<!-- 配置Spring配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/app.xml</param-value> </context-param>
After completing the above configuration, let's write a simple servlet and configure the Spring annotations:
package org.zero01.test;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Component("login")@WebServlet("/login")public class LoginServlet extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { }}
Then write a test servlet to see if you can get the instance object from the spring container, and in the Web project we can get the spring management object through the Webapplicationcontextutils class:
Package Org.zero01.test;import Org.springframework.web.context.webapplicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Org.zero01.pojo.student;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Java.io.ioexception;import Java.io.PrintWriter; @WebServlet ("/test") public class Testservlet extends HttpServlet { protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws IOException {//Get Spring Management Objects in Web engineering Webapplicationcontext Webapplicationcontext = Webapplicationcontextutils.getwebapplicationcontext ( This.getservletcontext ()); Similarly we can use this management object to get the instance object we need loginservlet Loginservlet = (loginservlet) webapplicationcontext.getbean ("login"); Student Student = (Student) webapplicationcontext.getbean ("Stu"); Print first to see if you can getTake the object PrintWriter PrintWriter = Resp.getwriter (); Printwriter.println (Loginservlet); PRINTWRITER.PRINTLN (student); }}
The output results are as follows:
[email protected][email protected]
As above, we can see that the object has been successfully obtained, it means that our configuration is not a problem, so that we can happily use spring in the Web project.
Briefly describe the loading process for the Webapplicationcontext object:
////Source code recreated from a. class file by IntelliJ idea//(powered by Fernflower D Ecompiler)//package Org.springframework.web.context;import javax.servlet.servletcontextevent;import Javax.servlet.servletcontextlistener;public class Contextloaderlistener extends Contextloader implements Servletcontextlistener {public Contextloaderlistener () {} public Contextloaderlistener (Webapplicationcontext Co ntext) {super (context); } public void Contextinitialized (Servletcontextevent event) {This.initwebapplicationcontext (Event.getservletcon Text ()); } public void Contextdestroyed (Servletcontextevent event) {This.closewebapplicationcontext (Event.getservletcont EXT ()); Contextcleanuplistener.cleanupattributes (Event.getservletcontext ()); }}
- The contextinitialized method of the listener class is called when ServletContext is initialized, and the method calls the Initwebapplicationcontext method and passes the ServletContext object. From the literal meaning of the method name, you can see that this method is used to initialize the Webapplicationcontext object.
- When Webapplicationcontext is initialized, The ServletContext object is given the initialization parameters we configured in Web. XML, the path to the spring configuration file, and the spring configuration file is loaded, and the Webapplicationcontext object is initialized after the successful load. Error if not loaded, initialization failed.
- Once the Webapplicationcontext object is initialized, it is stored in the properties of the ServletContext, where the entire loading process is completed.
- But since we don't know what the key/value is, we can't get the Webapplicationcontext object directly in the ServletContext, Instead, you have to use the tool class webapplicationcontextutils provided by spring to get
Multiple Spring configuration files
In some cases, we may need multiple configuration files, each configured with different modules, as follows:
When you need to introduce these profiles to a total configuration file, you can use the following statement:
<import resource="app-aop.xml"/><import resource="app-ioc.xml"/><import resource="app-tran.xml"/>
Spring Configuration Properties File
Spring supports the use of property files to configure parameters, but this use of property files to configure parameters is not used much, because it is very chicken, but also cause the scattered property files everywhere. However, it is possible to use it in some special cases, so it is also documented here by configuring the parameters of the data source object to demonstrate how to configure the properties file through Spring:
First create a property file Datasourceinfo.properties, with the following file contents:
database.driver=com.mysql.jdbc.Driverdatabase.url=jdbc:mysql:///schooldatabase.user=rootdatabase.pw=your_passworddatabase.max.pool.size=10database.min.pool.size=1database.loginTimeout=2000
Then edit the spring configuration content as follows:
<?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" Xsi:schemalo cation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd "> <!--Configuration Properties file path--<bean class=" Org.springframework.beans.factory.config.Prope Rtyplaceholderconfigurer "> <property name=" Locations "> <array> <VALUE&G t;datasourceinfo.properties</value> </array> </property> </bean> <!--with Data source Object--<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" p:driverclass= "${data Base.driver} "p:jdbcurl=" ${database.url} "p:user=" ${database.user} "p:password=" ${DATABASE.PW} " P:maxpoolsize= "${database.max.pool.size} "p:minpoolsize=" ${database.min.pool.size} "p:logintimeout=" ${database.logintimeout} "/></bea Ns>
The test code is as follows:
package org.zero01.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("app.xml"); DataSource dataSource = (DataSource) app.getBean("dataSource"); try { Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } catch (SQLException e) { e.printStackTrace(); } }}
Printing results:
[email protected]
As you can see from the print results, the data source object has been successfully taken out. However, from the entire configuration process you can see that with spring, the use of the properties file to configure parameters is somewhat mealy, these parameters can be directly configured in the spring configuration file, and one of the purposes of spring is to avoid the existence of a large number of property files.
Spring initialization classes in Web projects
If you want to initialize a class when the Tomcat server starts, and invoke a method in that class, you can do so by implementing the two interfaces in spring. The first is the Initializingbean interface, where the class that implements the interface is initialized and invokes the Afterpropertiesset method in the Tomcat server when it is started:
package org.zero01.test;import org.springframework.beans.factory.InitializingBean;public class InitBean implements InitializingBean { public void afterPropertiesSet() throws Exception { System.out.println("我被初始化了 —— InitializingBean"); }}
The other interface is Applicationlistener, the method of this interface has the data source parameter, so this method can do more things, and when you have some logic that must wait until all the beans have been processed before the execution, it is appropriate to use this interface, The method of this interface is called after all the beans have been processed:
package org.zero01.test;import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;public class AppInit implements ApplicationListener{ public void onApplicationEvent(ApplicationEvent applicationEvent) { System.out.println("我被初始化了 —— ApplicationListener"); }}
Then you need to configure these two classes, the spring configuration file content is as follows:
<?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 class="org.zero01.test.AppInit"/> <bean class="org.zero01.test.InitBean"/></beans>
After the configuration is complete, the Tomcat server starts, and the Tomcat server starts with the following output:
As you can see, the class that implements the Initializingbean interface to implement the Applicationlistener interface is initialized first. So there are some differences between them, which interface needs to be used according to the specific business scenario.
Get ApplicationContext or Beanfacrory objects by implementing an interface
The ApplicationContext object is obtained by implementing an interface with the following code:
package org.zero01.test;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class Test implements ApplicationContextAware { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { LoginServlet loginServlet = (LoginServlet) applicationContext.getBean("login"); }}
The Beanfacrory object is obtained by implementing an interface with the following code:
package org.zero01.test;import org.springframework.beans.BeansException;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.BeanFactoryAware;public class Test implements BeanFactoryAware { public void setBeanFactory(BeanFactory beanFactory) throws BeansException { LoginServlet loginServlet = (LoginServlet) beanFactory.getBean("login"); }}
Some fragmented knowledge of spring.