在开放SpringBoot项目时, 需要在启动后加载一些资源,或者是把一些热数据放到缓存中
如果不需要使用到springIOC中的bean时, 可以用 static ,或者是构造方法加载这些资源
如果需要使用IOC中的bean时
1. @PostConstruct
PostConstruct
注解使用在方法上,这个方法在对象依赖注入初始化之后执行。
2. CommandLineRunner 和 ApplicationRunner
SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner
和ApplicationRunner
。
这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner
的run方法入参为ApplicationArguments
,为CommandLineRunner
的run方法入参为String数组。
ApplicationArguments
官方文档解释为:
Provides access to the arguments that were used to run a SpringApplication.
在Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(…)
的应用参数。
3. … Aware 类
这些Aware类基本都是做一些特定事件的, 当然不管它原来是干嘛的, 它只要是在启动后执行, 就可以做一些自己想做的事情呗
执行顺序
@Component
public class Test implements ApplicationRunner, CommandLineRunner, ApplicationContextAware, BeanNameAware
{
@PostConstruct
public void run ()
{
System.err.println("PostConstruct");
}
@Override
public void run(ApplicationArguments args) throws Exception
{
System.err.println("ApplicationRunner");
}
@Override
public void run(String... args) throws Exception
{
System.err.println("CommandLineRunner");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
System.err.println("ApplicationContextAware");
}
@Override
public void setBeanName(String s)
{
System.err.println("BeanNameAware");
}
}
BeanNameAware
> ApplicationContextAware
> PostConstruct
> ApplicationRunner
> CommandLineRunner