1.ApplicationContextAware接口
ApplicationContext对象是Spring开源框架的上下文对象实例,在项目运行时自动装载Handler内的所有信息到内存。基于SpringBoot平台完成ApplicationContext对象的获取,并通过实例手动获取Spring管理的bean。
ApplicationContextAware接口的方式获取ApplicationContext对象实例,但并不是SpringBoot特有的功能,早在Spring3.0x版本之后就存在了这个接口,在传统的Spring项目内同样是可以获取到ApplicationContext实例的。
/**
* Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
*@Component不能去掉,否则无法调用setApplicationContext方法
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 获取application上下文对象
* @return
*/
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
/**
* 通过name获取bean
* @param beanName
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
/**
* 通过class获取bean
* @param requiredType
* @return
*/
public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}
private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
【上述代码注意实现】(1)ApplicationContextProvider类上的@Component注解是不可以去掉的,去掉后Spring就不会自动调用setApplicationContext方法来为我们设置上下文实例。
(2)我们把SpringContextHolder作为工具类,使用SpringContextHolder.getBean()方式直接调用获取。
2.CommandLineRunner接口
在实际应用中,我们会在项目服务启动的时候就去加载一些数据或者做一些事情这样的需求。为了解决这个问题,springboot为我们提供了一个方法,通过实现接口CommandLineRunner来实现。
**
* 服务器启动时执行
*/
@Component
public class MyStartRunning implements CommandLineRunner
{
@Autowired
private IDeptService deptService;
@Override
public void run(String... args) throws Exception
{
System.out.println("============服务器启动时执行================");
for (String arg:args){
//args参数数组是启动传入进来的
System.out.println("========执行的参数====="+arg);
}
Dept dept = deptService.selectById(25);
System.out.println("=======dept:======="+dept.toString());
}
}