美文网首页
Servlet3.0特性下Spring配置

Servlet3.0特性下Spring配置

作者: 無式 | 来源:发表于2017-07-05 09:08 被阅读0次

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

相关文章

网友评论

      本文标题:Servlet3.0特性下Spring配置

      本文链接:https://www.haomeiwen.com/subject/wxvfhxtx.html