zoukankan      html  css  js  c++  java
  • @PostConstruct commandLineRunner ApplicationRunner 初步探索

    感谢作者:https://blog.csdn.net/weixin_42465125/article/details/88560320

    1. 与@PostConstruct 相对应的是@PreDestroy 。

    在spring 中,构造器Constructor,@Autowired,@Postconstruct,@PostConstruct 实在构造函数之后执行,@Autowired 是注入依赖的,肯定是有了对象才能注入,Construct 优先于@Autowired。

    Construct>>@Autowired>>@postConstruct

    如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

    @SpringBootApplication
    public class SpringbootMailApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(SpringbootMailApplication.class, args);
        }
     
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
     
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
     
        ListOperations<String, Object> opsForList;
     
        ValueOperations<String, String> opsForString;
     
        /**
         * CommandLineRunner、ApplicationRunner 接口是在容器启动成功后的最后一步回调(类似开机自启动)
         * 
         * 接口被用作将其加入spring容器中时执行其run方法。多个CommandLineRunner可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致。
         */
        // 启动后执行的功能,可以用来初始化一些东西,这种情况下面明显使用@Bean来玩就比较方便,
        // 比起去创建一个新的类实现CommandLineRunner来说更方便[继承的使用方法参考:https://www.jianshu.com/p/5d4ffe267596,https://www.jianshu.com/p/5d4ffe267596]
        @Bean
        CommandLineRunner commandLineRunner(RedisTemplate<String, Object> redisTemplate) {
            return new CommandLineRunner() {
                @Override
                public void run(String... args) throws Exception {
                    opsForList = redisTemplate.opsForList();
                }
            };
        }
     
        // 启动后执行的功能,可以用来初始化一些东西,这种情况下面明显使用@Bean来玩就比较方便,比起去创建一个新的类实现CommandLineRunner来说更方便,借助Lamdab更爽
        @Bean
        CommandLineRunner commandLineRunnerId01(RedisTemplate<String, Object> redisTemplate) {
            return args -> {
                opsForList = redisTemplate.opsForList();
                opsForString = stringRedisTemplate.opsForValue();
            };
        }
     
        @Bean
        ApplicationRunner applicationRunner() {
            return new ApplicationRunner() {
                @Override
                public void run(ApplicationArguments args) throws Exception {
                    opsForList = redisTemplate.opsForList();
                }
            };
        }
    }
     
  • 相关阅读:
    Unity 摄像机旋转跟随缩放控制
    Unity 协程深入解析与原理
    好看的滚动条
    ES6编译问题SyntaxError: Unexpected token import
    Axure rp8 注册码,亲测可以用! 可用给个赞呗!!
    angular 项目中遇到rxjs error TS1005:';'
    window 查看端口 杀端口
    angular 中嵌套 iframe 报错
    js 快速生成数组的方法
    ng-packagr 不能全部打包文件
  • 原文地址:https://www.cnblogs.com/dousil/p/14636116.html
Copyright © 2011-2022 走看看