Spring Web工程web.xml零配置即使用Java Config + Annotation

news/2024/11/15 3:00:30/

摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Config方式去替换以前冗余的XML格式文件的配置方式;

在开始之前,我们需要注意一下,要基于Java Config实现无web.xml的配置,我们的工程的Servlet必须是3.0及其以上的版本;

1、我们要实现无web.xml的配置,只需要关注实现WebApplicationInitializer这个接口,以下为Spring源码:

复制代码
public interface WebApplicationInitializer {/*** Configure the given {@link ServletContext} with any servlets, filters, listeners* context-params and attributes necessary for initializing this web application. See* examples {@linkplain WebApplicationInitializer above}.* @param servletContext the {@code ServletContext} to initialize* @throws ServletException if any call against the given {@code ServletContext}* throws a {@code ServletException}*/void onStartup(ServletContext servletContext) throws ServletException;}
复制代码

 

2、我们这里先不讲他的原理,只要我们工程中实现这个接口的类,Spring容器在启动时候就会监听到我们所实现的这个类,从而读取我们的配置,就如读取web.xml一样,我们的实现类如下所示:

复制代码
public class WebProjectConfigInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext container) {initializeSpringConfig(container);initializeLog4jConfig(container);initializeSpringMVCConfig(container);registerServlet(container);registerListener(container);registerFilter(container);}private void initializeSpringConfig(ServletContext container) {// Create the 'root' Spring application contextAnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();rootContext.register(AppConfiguration.class);// Manage the life cycle of the root application contextcontainer.addListener(new ContextLoaderListener(rootContext));}private void initializeSpringMVCConfig(ServletContext container) {// Create the spring rest servlet's Spring application contextAnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();dispatcherContext.register(RestServiceConfiguration.class);// Register and map the spring rest servletServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",new DispatcherServlet(dispatcherContext));dispatcher.setLoadOnStartup(2);dispatcher.setAsyncSupported(true);dispatcher.addMapping("/springmvc/*");}private void initializeLog4jConfig(ServletContext container) {// Log4jConfigListenercontainer.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");container.addListener(Log4jConfigListener.class);PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);}private void registerServlet(ServletContext container) {initializeStaggingServlet(container);}private void registerFilter(ServletContext container) {initializeSAMLFilter(container);}private void registerListener(ServletContext container) {container.addListener(RequestContextListener.class);}private void initializeSAMLFilter(ServletContext container) {FilterRegistration.Dynamic filterRegistration = container.addFilter("SAMLFilter", DelegatingFilterProxy.class);filterRegistration.addMappingForUrlPatterns(null, false, "/*");filterRegistration.setAsyncSupported(true);}private void initializeStaggingServlet(ServletContext container) {StaggingServlet staggingServlet = new StaggingServlet();ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);dynamic.setLoadOnStartup(3);dynamic.addMapping("*.stagging");}
}
复制代码

3、以上的Java Config等同于如下web.xml配置:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><context-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></context-param><context-param><param-name>contextConfigLocation</param-name><param-value>com.g360.configuration.AppConfiguration</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param> <param-name>log4jConfigLocation</param-name> <param-value>file:${rdm.home}/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet><description>staggingServlet</description><display-name>staggingServlet</display-name><servlet-name>staggingServlet</servlet-name><servlet-class>com.g360.bean.interfaces.StaggingServlet</servlet-class></servlet><servlet-mapping><servlet-name>staggingServlet</servlet-name><url-pattern>*.stagging</url-pattern></servlet-mapping><servlet><servlet-name>SpringMvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></init-param><init-param><param-name>contextConfigLocation</param-name><param-value>com.g360.configuration.RestServiceConfiguration</param-value></init-param><load-on-startup>1</load-on-startup><async-supported>true</async-supported></servlet><servlet-mapping><servlet-name>SpringMvc</servlet-name><url-pattern>/springmvc/*</url-pattern></servlet-mapping><filter> <filter-name>SAMLFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><async-supported>true</async-supported></filter> <filter-mapping> <filter-name>SAMLFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list>
</web-app>
复制代码

4、我们分类解读,在web.xml配置里面我们配置的Web Application Context

复制代码
    <context-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></context-param><context-param><param-name>contextConfigLocation</param-name><param-value>com.g360.configuration.AppConfiguration</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
复制代码

就等价于Java Config中的

复制代码
private void initializeSpringConfig(ServletContext container) {// Create the 'root' Spring application contextAnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();rootContext.register(AppConfiguration.class);// Manage the life cycle of the root application contextcontainer.addListener(new ContextLoaderListener(rootContext));
}
复制代码

如此推断,在web.xml配置里面我们配置的log4j

复制代码
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>file:${rdm.home}/log4j.properties</param-value> 
</context-param> 
<listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
</listener> 
复制代码

就等价于Java Config的

    private void initializeLog4jConfig(ServletContext container) {// Log4jConfigListenercontainer.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");container.addListener(Log4jConfigListener.class);PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);}

类此,在web.xml配置里面我们配置的Spring Web(Spring Restful)

复制代码
    <servlet><servlet-name>SpringMvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></init-param><init-param><param-name>contextConfigLocation</param-name><param-value>com.g360.configuration.RestServiceConfiguration</param-value></init-param><load-on-startup>1</load-on-startup><async-supported>true</async-supported></servlet><servlet-mapping><servlet-name>SpringMvc</servlet-name><url-pattern>/springmvc/*</url-pattern></servlet-mapping>
复制代码

就等价于Java Config中的

复制代码
private void initializeSpringMVCConfig(ServletContext container) {// Create the spring rest servlet's Spring application contextAnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();dispatcherContext.register(RestServiceConfiguration.class);// Register and map the spring rest servletServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",new DispatcherServlet(dispatcherContext));dispatcher.setLoadOnStartup(2);dispatcher.setAsyncSupported(true);dispatcher.addMapping("/springmvc/*");
}
复制代码

再此,在web.xml配置里面我们配置的servlet

复制代码
    <servlet><description>staggingServlet</description><display-name>staggingServlet</display-name><servlet-name>staggingServlet</servlet-name><servlet-class>com.g360.bean.interfaces.StaggingServlet</servlet-class></servlet><servlet-mapping><servlet-name>staggingServlet</servlet-name><url-pattern>*.stagging</url-pattern></servlet-mapping>
复制代码

就等价于Java Config中的

    private void initializeStaggingServlet(ServletContext container) {StaggingServlet staggingServlet = new StaggingServlet();ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);dynamic.setLoadOnStartup(3);dynamic.addMapping("*.stagging");}

后面以此类推,在这里不加详述了;

5、如上面所说的,我们对Web 工程的整体配置都依赖于AppConfiguration这个配置类,下面是使用@Configuration 配置类注解的,大家使用过的,以此类推,都比较清楚,

这里就不加赘述了;

复制代码
@Configuration
@EnableTransactionManagement
@EnableAsync
@EnableAspectJAutoProxy
@EnableScheduling
@Import({ RestServiceConfiguration.class, BatchConfiguration.class, DatabaseConfiguration.class, ScheduleConfiguration.class})
@ComponentScan({ "com.service", "com.dao", "com.other"})
public class AppConfiguration
{private Logger logger = LoggerFactory.getLogger(AppConfiguration.class);/*** */public AppConfiguration (){// TODO Auto-generated constructor stublogger.info("[Initialize application]");Locale.setDefault(Locale.US);}}
复制代码

还有就是对Spring Web配置的类RestServiceConfiguration ,个人可根据自己的实际项目需求在此配置自己的视图类型以及类型转换等等

复制代码
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = { "com.bean" })
public class RestServiceConfiguration extends WebMvcConfigurationSupport {@Beanpublic RequestMappingHandlerAdapter requestMappingHandlerAdapter() {RequestMappingHandlerAdapter handlerAdapter = super.requestMappingHandlerAdapter();return handlerAdapter;}@Beanpublic LocaleChangeInterceptor localeChangeInterceptor() {return new LocaleChangeInterceptor();}@Beanpublic LogAspect logAspect() {return new LogAspect();}
}
复制代码

至此,我们的 web.xml使用Java Config零配置就完了

https://my.oschina.net/521cy/blog/702864


http://www.ppmy.cn/news/558089.html

相关文章

开源地址

开源中国&#xff1a;http://www.oschina.net/project/zh csdn专访&#xff1a;http://blog.csdn.net/blogdevteam/article/list/2 iteye&#xff1a;http://www.iteye.com/magazines/ java快速开发平台&#xff0c;java二次开发平台 G4Studio fastunit java-hi beetl o…

腾讯云检测到你的服务器对其他服务器的攻击行为

某天突然收到腾讯云的邮件说我是在攻击别人 第一时间反应是我的服务器被入侵当作肉鸡了&#xff0c;然后排查ssh有没有被破解&#xff0c;全盘扫描病毒&#xff0c;检测任务计划&#xff0c;进程等&#xff0c;结果没有什么异常。 第二天打开自己家的路由器发现内网穿透客户端…

宇视警戒球智能跟踪功能配置方法

警戒球智能跟踪功能 名词解释: 智能跟踪&#xff1a;当有人进入监控区域时&#xff0c;警戒球会锁定目标&#xff0c;持续跟踪。常用于少有人出现的场所&#xff0c;可以大大解决巡视难的问题。#本功能可单机使用# 支持的型号&#xff1a;宇视警戒球全系列产品 智能跟踪功能…

服务器被检测出挖矿

有位朋友说&#xff0c;他服务器使用的好好的&#xff0c;服务商突然封了他服务器&#xff0c;说是被检测出挖矿&#xff0c;这位朋友一脸懵“我开游戏的&#xff0c;挖什么矿”。突然地关停服务器导致这位朋友损失惨重&#xff0c;那么为什么会被检测出挖矿&#xff0c;以及怎…

服务器被打了要报警嘛

游戏服务器在现如今电子竞技发达的今天越发火爆&#xff0c;但是被攻击也是很常见的&#xff0c;特别事游戏新上线时&#xff0c;都要承受的住外来压力&#xff0c;玩家数量的激增&#xff0c;被黑客攻击等等。在这里我来说说游戏服务器为什么老被攻击和怎么防御恶意攻击。 游…

选择高防服务器的重要性 ,游戏行业必看

选择高防服务器的重要性&#xff01;游戏行业必看&#xff01;&#xff01;&#xff01; 众所周知高防服务器比普通服务器更好&#xff0c;但意味着价格更贵&#xff0c;那么选择高防服务器有哪些好处呢&#xff1f;因为流水量大&#xff0c;现金流动迅速&#xff0c;游戏行业…

记录一次云服务器被劫持下载了挖矿病毒的处理过程

etc被篡改导致系统中病毒 起因: 一年前买的阿里云服务器 , 买了没多久 , 因为没做什么安全措施 , 然后就莫名奇妙服务器被劫持 , 在上面下载了挖矿的一些脚本 ,当时做的处理方式 简单粗暴 直接重置了我的阿里云服务器 , 并且改了密码 , 同时在阿里云的服务器控制台 -> 安全…

排查腾讯云服务器被挖矿病毒【pnscan】挟持

一、问题发现 最新在使用腾讯云部署项目应用&#xff0c;具体方式为docker部署。今天早上发现腾讯云发来一条报警信息&#xff1a; 看到信息中说到攻击行为&#xff0c;怀疑是否中了病毒&#xff0c;决定排查一下问题。 二、排查过程 首先登录腾讯云服务器控制台&#xff0…