Springboot项目资源初始化操作常用方法

1、CommandLineRunner、ApplicationListener

SpringBoot提供了CommandLineRunner和ApplicationRunner接口。当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
两者的区别在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。

@Component
public class MyListener1 implements CommandLineRunner {
    @Autowired
    private ShopInfoMapper shopInfoMapper;
    @Override
    public void run(String... args) throws Exception {
        //使用spring容器中的bean
        //System.out.println(shopInfoMapper.selectById("1").getShopName());
        System.out.println("项目启动OK");
    }
}

----------------------------------------------------------

@Component
public class MyListener1 implements ApplicationRunner {
    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //使用spring容器中的bean
        //System.out.println(shopInfoMapper.selectById("1").getShopName());
        System.out.println("项目启动OK");
    }
}

2、InitializingBean

InitializingBean 是 Spring 提供的一个接口,只包含一个方法 afterPropertiesSet()。凡是实现了该接口的类,当其对应的 Bean 交由 Spring 管理后,当其必要的属性全部设置完成后,Spring 会调用该 Bean 的 afterPropertiesSet()。

@Component
public class MyListener1 implements InitializingBean {
    @Autowired
    private ShopInfoMapper shopInfoMapper;
    @Override
    public void afterPropertiesSet() {
        //使用spring容器中的bean
        //System.out.println(shopInfoMapper.selectById("1").getShopName());
        System.out.println("项目启动OK");
    }
}

3、@PostConstruct

在具体Bean的实例化过程中执行,@PostConstruct注解的方法,会在构造方法之后执行,顺序为Constructor > @Autowired > @PostConstruct > 静态方法,所以这个注解就避免了一些需要在构造方法里使用依赖组件的尴尬。

注意点如下

  • 只有一个非静态方法能使用此注解

  • 被注解的方法不得有任何参数

  • 被注解的方法返回值必须为void

  • 被注解方法不得抛出已检查异常

  • 此方法只会被执行一次

    @Component public Class AAA {
    @Autowired
    private BBB b;
    public AAA() {
    System.out.println("此时b还未被注入: b = " + b);
    }
    @PostConstruct
    private void init() {
    System.out.println("此时b已经被注入: b = " + b);
    } }

4、ApplicationListener

ApplicationListener 就是spring的监听器,能够用来监听事件,典型的观察者模式。如果容器中有一个ApplicationListener Bean,每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发。这种事件机制都必须需要程序显示的触发。其中spring有一些内置的事件,当完成某种操作时会发出某些事件动作。比如监听ContextRefreshedEvent事件,当所有的bean都初始化完成并被成功装载后会触发该事件,实现ApplicationListener接口可以收到监听动作,然后可以写自己的逻辑。同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。所以也能做到资源的初始化加载。

@Component
public class MyListener1 implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        
        //打印出每次事件的名称
        System.out.println(applicationEvent.toString());
        
        if (applicationEvent instanceof ApplicationReadyEvent) {
            System.out.println("项目启动OK");
        }
    }
}

 

参考:http://www.likecs.com/show-63032.html

评论

暂无评论