一剪侮、這個接口有什么用?
當一個類實現(xiàn)了這個接口(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);