一、这个接口有什么用?
当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext =applicationContext;
}
/**
* 得到Spring 上下文
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注示请在application-context.xml中定义SpringContextHolder");
}
}
/**
* 通过Spring Bean name 得到Bean
* @param name bean 上下文定义名 */
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
* 通过类型得到Bean
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
return (T) applicationContext.getBeansOfType(clazz);
}
@Service(UserService.name)
public class UserServiceImpl implements UserService
userService= SpringContextHolder.getBean(UserService.name);