Servlet3.0特性下Spring配置

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安全验证

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容