zoukankan      html  css  js  c++  java
  • 实现在项目启动后或是生成对象后完成某些执行的功能实现CommandLineRunner接口和注解@PostConstruct

      在项目中我们有时候需要实现项目启动后就执行的功能,比如将热点数据存入redis中。

    方式一:定义一个类实现CommandLineRunner接口,实现功能的代码在run方法中。cnblogs中参考

    补充:SpringBoot在项目启动后会遍历所有实现CommandLineRunner的实体类并执行run方法,如果需要按照一定的顺序去执行,那么就需要在实体类上使用一个@Order注解(或者实现Order接口)来表明顺序。

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class RedisDataRunner implements CommandLineRunner {
        @Autowired
        private SetRedisData redisData;
    
        @Override
        public void run(String... strings) throws Exception {
            redisData.setOrgData();
        }
    }
    View Code

    方法二:在方法中增加注解@PostConstruct,修饰一个非静态的void()方法。csdn中参考链接

    @PostConstruct注解的方法会在依赖注入完成后被自动调用:Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    @Component
    public class RedisDataRunner {
    
        @Autowired
        private SetRedisData redisData;
    
        public static final ExecutorService pool = Executors.newFixedThreadPool(10);
    
        @PostConstruct
        public void init() {
            
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    redisData.setOrgData();
                }
            });
        }
    }
    View Code
  • 相关阅读:
    HelloWorld
    CSS盒子模型
    CSS选择器
    Win右键管理员权限的获取
    本地存储
    python模块以及导入出现ImportError: No module named 'xxx'问题
    python pexpect 学习与探索
    VI查找与替换
    python 中__name__ = '__main__' 的作用
    python 脚本传递参数
  • 原文地址:https://www.cnblogs.com/guobm/p/13564883.html
Copyright © 2011-2022 走看看