美文网首页
SpringBoot常用注解

SpringBoot常用注解

作者: X_xxieRiemann | 来源:发表于2019-07-15 18:50 被阅读0次

    @SpringBootApplication :

    用在引导类上

    • @SpringBootConfiguration:声明当前类是SpringBoot应用的配置类,项目中只能有一个。所以一般我们无需自己添加。
    • @EnableAutoConfiguration:开启spring应用程序的自动配置,SpringBoot基于你所添加的依赖和你自己定义的bean,试图去猜测并配置你想要的配置。比如我们引入了spring-boot-starter-web,而这个启动器中帮我们添加了tomcat、SpringMVC的依赖。此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!这个自动配置可以在依赖spring-boot-autoconfigure中查看
    • @ComponentScan:开启注解扫描,如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包。被@controller@service@repository@component@Configuration注解的类,都会把这些类纳入进spring容器中进行管理,可以无需使用@Bean
    @SpringBootApplication
    public class TestApplication {
        public static void main(String[] args) {
            SpringApplication.run(TestApplication.class, args);
        }
    }
    

    @RestController

    在XxxxController类使用,相当于@ResponseBody@Controller联用
    在什么情况下使用@ResponseBody 注解?

    @RestController
    public class HelloController {
    
        @GetMapping("show")
        public String test(){
            return "hello Spring Boot!";
        }
    }
    

    @service

    用于事务

    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        public User queryById(Long id){
            return this.userMapper.selectByPrimaryKey(id);
        }
    
        @Transactional
        public void deleteById(Long id){
            this.userMapper.deleteByPrimaryKey(id);
        }
    }
    

    @repository

    持久层

    @component

    泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

    //拦截器
    @Component
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("preHandle method is running!");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle method is running!");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion method is running!");
        }
    }
    

    java配置

    @Configuration:声明一个类作为配置类,然后Spring容器会根据它来生成IoC容器去配置Bean。用于XxxxConfiguration类中。
    @PropertySource:指定外部属性文件。@PropertySource("classpath:jdbc.properties")
    @Value:属性注入
    @Bean:声明在方法上,将方法的返回值加入Bean容器,Spring会自动调用该方法,将方法的返回值加入Spring容器中。如果没有带参数,则会以函数名(如例子中的dataSource)作为Bean的名称保存,也可以对name属性进行赋值,主动配置名字。
    @Autowired:在任意位置从Spring容器中提取并注入到属性当中

    @Configuration
    @PropertySource("classpath:jdbc.properties")
    public class JdbcConfiguration {
    
        @Value("${jdbc.url}")
        String url;
        @Value("${jdbc.driverClassName}")
        String driverClassName;
        @Value("${jdbc.username}")
        String username;
        @Value("${jdbc.password}")
        String password;
    
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(url);
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    }
    

    测试

    @RestController
    public class HelloController {
    
        @Autowired
        private DataSource dataSource;
    
        @GetMapping("show")
        public String test(){
            return "hello Spring Boot!";
        }
    }
    

    Spring其他装配Bean的方法

    除了@Bean外,Spring还允许扫描装配Bean到IoC容器中。
    @Component:标明哪个类被扫描进入Spring IoC容器中。
    @ComponentScan:标明采用何种策略去扫描装配Bean。一般直接用@SpringBootApplication代替

    SpringBoot的属性注入方式

    @ConfigurationProperties(prefix = "jdbc")
    SpringBoot的属性注入方式,支持各种java基本数据类型及复杂类型的注入。要求修饰的类里面的命名与配置一致,且必须有set方法,从而可以省去@Value

    @EnableConfigurationProperties(JdbcProperties.class)
    在其他类注入@ConfigurationProperties配置过的类时,需要添加该注解。

    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
        private String url;
        private String driverClassName;
        private String username;
        private String password;
        // ... 略
        // getters 和 setters
    }
    

    注入

    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfiguration {
    
        @Autowired
        private JdbcProperties jdbcProperties;
    
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    
    }
    

    @RequestMapping

    配置 Web 请求的映射,用{}来表明它的变量部分

        @RequestMapping(value = {  
            "",  
            "/page",  
            "page*",  
            "view/*,**/msg"  
        })
    

    @GetMapping

    @GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

    @PostMapping

    @PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

    @PathVariable

    @RestController
    @RequestMapping("test")
    public class MyController {
    
        @Autowired
        private User user;
    
        @GetMapping("{subPath}")
        public String test(@PathVariable("subPath") String subPath) {
            if (subPath.equals("all")) {
                return user.toString();
            } else if (subPath.equals("name")) {
                return user.getUserName();
            } else {
                return null;
            }
        }
    }
    
    @RequestMapping("/user/{username}/blog/{blogId}")
    @ResponseBody
    public String getUerBlog(@PathVariable String username , @PathVariable int blogId) {
        return "user: " + username + "blog->" + blogId;
    }
    

    这种情况下,Spring能够根据名字自动赋值对应的函数参数值,也可以在@PathVariable中显示地表明具体的URL变量值。
    在默认情况下,@PathVariable注解的参数可以是一些基本的简单类型:int,long,Date,String等,Spring能根据URL变量的具体值以及函数参数的类型来进行自动转换,例如/user/fpc/blog/1,会将“fpc”的值赋给username,而1赋值给int变量blogId。

    @RequestParam

    @RestController
    @RequestMapping("/test")
    public class Test {
    
        @GetMapping("test.do")
        // 指定将username参数的值传递到该方法的name参数上
        public void test(@RequestParam(name = "username") String name) {
            System.out.println(name);
        }
    
        @GetMapping("user.do")
        // 指定将username参数的值传递到该方法的user参数上,alias参数的值则传递到该方法的a参数上
        public void userAndAlias(@RequestParam(name = "username")String user, @RequestParam(name = "alias")String a) {
            System.out.println(user);
            System.out.println(a);
        }
    }
    

    @RequestMapping与@RequestParam注解

    相关文章

      网友评论

          本文标题:SpringBoot常用注解

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