@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();
            }
        };
    }
}
 
原文地址:https://www.cnblogs.com/dousil/p/14636116.html