zoukankan      html  css  js  c++  java
  • 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层。

  • 相关阅读:
    前后端不分离的springboot项目问题:页面框架问题
    SpringBoot使用Filter过滤器处理是否登录的过滤时,用response.sendRedirect()转发报错
    mysql千万级数据优化查询
    java进阶学习的一些思路
    java的List列表转成Tree(树形)结构列表
    cmd 一键获取 所有连接过的wifi 密码
    SQLMap用户手册【超详细】
    Python:SQLMAP参数中文解释
    初识sql注入及sqlmap
    wwwscan网站目录文件批量扫描工具
  • 原文地址:https://www.cnblogs.com/FJH1994/p/7064575.html
Copyright © 2011-2022 走看看