SpringBoot 注解

 1,获取配置文件自定义参数的值 @Value

import org.springframework.beans.factory.annotation.Value;

@Value("${server.port}")
private String port;

@RequestMapping("/index")
public String index() {
return port;
}

2,@Async 配和 @EnableAsync

    @RequestMapping("/insertUser")
    public String insertUser(){
        log.info("1");
        User user = new User();
        user.setUsername("chris");
        user.setSex("male");
        userService.insertUser(user);
        log.info("4");
        return "success";
    }

在userService 层添加:

    @Transactional
    @Async   //相当于这个方法开辟了新的线程去执行
    public void insertUser(User user) {
        log.info("2");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        userMapper.insertUser(user);
        log.info("3");
    };

不加@Async 配和 @EnableAsync 执行顺序1,2,3,4

加了之后,1,4,2,3,

需要注意的是@Async 所在的bean 需要被注入到Spring 容器中,这样项目初始化的时候,通过扫包将有@Async 的bean 加入到容器中,访问请求的时候,通过AOP 才知道哪个方法加上了@Async,才能使其生效。不能直接在controller 上同一个类里面写两个方法实现@Async

 3,@Scheduled  定时任务    启动类加上 @EnableScheduling

@Component
public class ScheduledTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }
}

支持cron 表达式

 @Scheduled(cron ="0 35 10,14,15 * * ?")    //每天10:35  ,14:35 ,16:35执行

https://www.cnblogs.com/linjiqin/archive/2013/07/08/3178452.html

原文地址:https://www.cnblogs.com/pickKnow/p/11200944.html