Servlet3.0环境下,提供给开发者一种基于class注解的web项目的配置方式,作为web.xml的补充或者替代,使得工程配置有更强的可读性:
public class DefaultWebApplicationInitializer implements
WebApplicationInitializer {
@Override
public void onStartup(ServletContext appContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(DefaultAppConfig.class);
appContext.addListener(new ContextLoaderListener(rootContext));
//注册dispatcher servlet
ServletRegistration.Dynamic dispatcher = appContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
这个类相当于原来的web.xml配置文件。
Spring的class配置
Spring及其生态圈也陆续支持此种方式的启动和配置。
Spring支持配置写成代码的形式以替代传统的xml配置,例如:
@Configuration
@ComponentScan(basePackages = "com.nd.myproject")
public class DefaultAppConfig {
}
@Configuration表明此为Spring配置类,@ComponentScan说明了Bean扫描路径。
- 常用注解说明:
@Configuration: 类似于spring配置文件,负责注册bean,对应的提供了@Bean注解。
@ComponentScan: 注解类查找规则定义<context:component-scan/>
@EnableAspectJAutoProxy: 激活Aspect自动代理<aop:aspectj-autoproxy/>
@Import@ImportResource: 关联其它Spring配置<import resource="" />
@EnableCaching:启用缓存注解<cache:annotation-driven/>
@EnableTransactionManagement: 启用注解式事务管理<tx:annotation-driven />
@EnableWebMvcSecurity: 启用SpringSecurity安全验证