BeanNameAware
,这个类能够在Spring容器加载的过程中将Bean的名字(id)赋值给变量。BeanNameAware
:能够获取bean的名称,即是idBeanFactoryAware
:获取BeanFactory实例ApplicationContextAware
:获取ApplicationContext
MessageSourceAware
:获取MessageSourceResourceLoaderAware
:获取ResourceLoader
EnvironmentAware
:获取Environment
ApplicationContextAware
这个接口了。ApplicationContextAware
的实现类如下/**
* 自定义一个实现类,一定要注入到容器中
*/
@Component
public class ApplicationContextAwareImpl implements ApplicationContextAware {
/**
* 容器启动的时候会调用这个方法,只需要将applicationContext设置即可
* @param applicationContext 容器启动会自动注入
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//将其设置到ApplicationContextUtil
ApplicationContextUtil.setApplicationContext(applicationContext);
}
}
ApplicationContextUtil
如下:import org.springframework.context.ApplicationContext;
/**
* ApplicationContext的工具类
*/
public class ApplicationContextUtil {
/**
* ApplicationContext对象,会ApplicationContextAwareImpl中的setApplicationContext方法中赋值
*/
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextUtil.applicationContext = applicationContext;
}
/**
* 根据类型获取指定的bean
* @param requiredType Class
* @param <T> 泛型
* @return
*/
public static <T> T getBean(Class<T> requiredType ){
return applicationContext.getBean(requiredType);
}
/**
* 根据名称和类型获取Bean
* @param name bean的id
* @param requiredType class
* @param <T>
* @return
*/
public static <T> T getBean(String name,Class<T> requiredType){
return applicationContext.getBean(name,requiredType);
}
}
StringRedisTemplate redisTemplate=ApplicationContextUtil.getBean("stringRedisTemplate",StringRedisTemplate.class);
Aware
,要向成功获取指定的对象,必备的条件如下:xxxAware
接口org.springframework.context.support.ApplicationContextAwareProcessor#invokeAwareInterfaces
,源码如下:private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}