• Spring 常用的注解


    Spring 常用的注解

    前言

    最近才体会到Spring注解配置的遍历,总结一下。

    SpringMVC配置

    @Configuration
    @EnableWebMvc
    @ComponentScan("cn.fjhdtp.maventest.controller")
    public class SpringMvcConfig {
        @Bean
        public InternalResourceViewResolver internalResourceViewResolver() {
            InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
            internalResourceViewResolver.setViewClass(JstlView.class);
            internalResourceViewResolver.setPrefix("/WEB-INF/views/");
            internalResourceViewResolver.setSuffix(".jsp");
            return internalResourceViewResolver;
        }
    }
    

    @Configuration表明这是一个配置类;@EnableWebMvc启用SpringMVC。

    web配置

    public class WebInitializer implements WebApplicationInitializer{
        public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
            AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(SpringMvcConfig.class);
            ctx.setServletContext(servletContext);
            ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
            servlet.addMapping("/");
            servlet.setLoadOnStartup(1);
        }
    }
    

    实现__WebApplicationInitializer__的类的__onStartup__方法会在Spring启动之后被执行,并且这个优先级在listener之前。可以用@Order(100)注解来配置执行的顺序,没有这个注解则代表是最先执行。

    @ComponentScan

    类似<context:component-scan />

    @ComponentScan(value = "cn.fjhdtp.maventest", excludeFilters = {
            @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Configuration.class, Controller.class}),
    })
    

    @PropertySource

    @Configuration结合使用,读取properties文件

    @PropertySources

    @PropertySources({
            @PropertySource(value = "classpath:jedis.properties")
    })
    

    @Value

    @PropertySource或者<context:property-placeholder/>结合使用,注入属性值。

    @Value("${redis.hostName:127.0.0.1}")
    private String hostName; // 主机名
    @Value("${redis.port:6379}")
    private int port; // 监听端口
    @Value("${redis.auth:}")
    private String password; // 密码
    @Value("${redis.timeout:2000}")
    private int timeout; // 客户端连接时的超时时间(单位为秒)
    

    @Controller

    @Controller表明这个类是一个controller,和@RequestMapping结合来配置映射的路径。

    @Component

    @Component表明这是一个Bean,但是如果知道属于那一层最好还是用@Service或者@Repository

    @Service

    用在Service层。

    @Repository

    用在Dao层。

  • 相关阅读:
    个人博客
    个人博客
    个人博客
    个人博客
    个人博客
    个人博客
    个人博客
    5.14
    5.13
    5.12
  • 原文地址:https://www.cnblogs.com/FJH1994/p/7064575.html
Copyright © 2020-2023  润新知