springboot 项目启动之后立即执行代码的方式

方式 ( 1 )
使用 @Bean 注解 因为@mapperScan注解的原因 所以项目启动之后会执行@Bean 来注入bean对象 可以设置返回值为 void 只做单纯的代码执行
@Component
public class StartupBeanRunner {
 
    @Autowired
    private TrendsScienceSendPeopleMapper trendsScienceSendPeopleMapper;
    @Bean
    public void testRunner(){
        System.out.println("项目启动了-------------------");
        System.out.println(trendsScienceSendPeopleMapper);
    }
}

启动测试: 项目启动断点就进去并且 能用 @Autowired 取出spring容器中的bean对象

 

方式 ( 2 )
实现 CommandLineRunner接口重写run方法 里面在项目完全执行后执行 run代码
@Component
public class StartupRunner implements CommandLineRunner {
 
    @Autowired
    private TrendsScienceSendPeopleMapper trendsScienceSendPeopleMapper;
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目启动了-------------------");
        System.out.println(trendsScienceSendPeopleMapper);
    }
 
 
}

断点测试与上方一致

 区别执行顺序问题 @Bean 比 实现 CommandLineRunner执行要早

 

https://blog.csdn.net/weixin_56576835/article/details/134011262

posted @ 2024-06-04 10:40  wq9  阅读(7)  评论(0)    收藏  举报