springboot启动时,扫描生成的对象会放在springboot容器中被管理,不过有时候我们在程序中需要通过类名,或者对象名,来获取到所需要使用的对象,这种情况我们就可以使用ApplicationContextAware来实现
示例:
package com.qingnian.spring.running;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class AwareClass implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("类被创建时自动执行");
this.applicationContext=applicationContext;
}
//通过name获取Bean
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
//通过class获取Bean
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
}
做个简单的小例子,改变Controller层自动注入的servide对象,从上下文获取
@Controller("good")
@Slf4j
public class GoodController {
@Autowired
private GoodService goodService;
@GetMapping("/getInfo/{id}")
@ResponseBody
public Good getOneInfo(@PathVariable Long id){
return goodService.selectOne(id);
}
}
改变后:
@Controller("good")
@Slf4j
public class GoodController implements ApplicationContextAware {
/*@Autowired
private GoodService goodService;*/
private static ApplicationContext applicationContext;
//通过name获取Bean
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("自动执行");
this.applicationContext=applicationContext;
}
@GetMapping("/getInfo/{id}")
@ResponseBody
public Good getOneInfo(@PathVariable Long id){
//通过对象名获取到这个接口对象
GoodService goodService = (GoodService)getBean("goodServiceImpl");
return goodService.selectOne(id);
}
}