spring项目在项目启动时初始化数据方式(包括调用service层)

下面两种方式可以在spring bean 加载完之后实现执行。
1、可以使用@PostConstruct注解,但是该注解如果要调用service层,service需要开启事务,同时,这个注解需要放在spring组件中@service、@Component等,被@PostConstruct修饰的方法会在加载Servlet的时候运行,类似于Serclet的inti()方法
2、实现ApplicationListener《ContextRefreshedEvent》接口
示例如下

public class TaskListener implements ApplicationListener {


    private static UserInfoService userInfoService = null;


    //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            userInfoService = event.getApplicationContext().getBean(UserInfoService.class);

            /** 具体业务代码 **/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(spring)