标签:
替代Web.XML的类
通过集成webApplicationInitialize完成启动
package com.travelsky.autotest.config.spring; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.DispatcherServlet; import com.travelsky.autotest.aop.RequestFilter; public class WebInit implements WebApplicationInitializer { @Override public void onStartup(ServletContext sc) throws ServletException { // Create the ‘root‘ Spring application context AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext(); application.scan("com.travelsky.autotest.config.spring");//扫描配置文件 // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(application));//把配置文件添加到WEB容器里面,相当于去读取了XXX.servlet.XML 文件 //CharacterEncodingFilter CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); FilterRegistration filterRegistration = sc.addFilter("characterEncodingFilter", characterEncodingFilter); filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");// sc.addFilter("requestFilter", RequestFilter.class).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/case/*");//过滤路径 添加过滤器
AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); ServletRegistration.Dynamic appServlet = sc.addServlet("appServlet", new DispatcherServlet(webContext));//配置dispatchservlet appServlet.setLoadOnStartup(1);//貌似只有1,0或者-1 appServlet.addMapping("/"); //配置请求的匹配方式 } }
XXX-servlet.XML(application-servlet.xml)的一个配置替代
XXX的servlet的配置主要还是依赖于去继承WebMvcConfigerAdapter的实现
package com.travelsky.autotest.config.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration//配置注解 @ComponentScan(basePackages="com.travelsky.autotest.*") @EnableWebMvc @EnableScheduling//启动定时器 @EnableAspectJAutoProxy(proxyTargetClass=true)//动态代理的注解启动 public class WebConfig extends WebMvcConfigurerAdapter{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resource/**").addResourceLocations("/resource/");//配置静态文件 } }
bean.xml的替代
通过@configuation和@Bean
在单元测试的情况下经常适用,我这里是启动保证数据库单例的一个例子
@Configuration public class MongoTemplateConfig { @Bean public MongoTemplate autoTestClient() { DataSource ds = new AutoTest_DefaultDB().build(new DataSource()); Mongo mongo = null; try { mongo = new MongoClient(ds.getIp(),ds.getPort()); } catch (UnknownHostException e) { throw new RuntimeException(e); } UserCredentials userCredentials = new UserCredentials(ds.getUsername(), ds.getPassword()); return new MongoTemplate(mongo, ds.getDatabaseName(), userCredentials); }
容器启动的时候加载的一个方案
通过继承InitializingBean的方式对afterPropertySet方法的重写,我这里是在启动的时候去查询数据库然后拿到值只有通过反射对一个对静态配置文件类的属性进行赋值
package com.travelsky.autotest.config.spring; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.travelsky.autotest.dao.entity.Config; import com.travelsky.autotest.dao.table.ConfigDao; @Component public class InitConfigration implements InitializingBean{ final static Logger logger = LoggerFactory.getLogger("InitConfigration"); @Autowired ConfigDao<Config> dao ; public void init() throws ClassNotFoundException { Class<?> clazz = Class.forName("com.travelsky.autotest.selenium.config.BaseConst"); for (Field f : clazz.getFields()) { try { if (f.getType().toString().equals("int")) { f.set(f.getName(), Integer.valueOf(dao.query("key", f.getName()).get(0).getValue())); } if (f.getType().toString().equals("class [Ljava.lang.String;")) { String temp = dao.query("key", f.getName()).get(0).getValue(); temp = temp.substring(1, temp.length() - 1); f.set(f.getName(), temp.split(",")); } if (f.getType().toString().equals("class java.lang.String")) { f.set(f.getName(), dao.query("key", f.getName()).get(0).getValue()); } } catch (Exception e) { logger.error(f.getName() + "从数据库提取报错"); } } } @Override public void afterPropertiesSet() throws Exception { init(); } }
spring4.0全注解配置的应用,以及一些我平时写项目的一些常用配置
标签:
原文地址:http://www.cnblogs.com/sunfan1988/p/4235250.html