Spring中的Aware
- Spring框架中提供了许多实现了Aware接口的类,这些类主要是为了辅助Spring访问容器中的数据,比如
BeanNameAware
,这个类能够在Spring容器加载的过程中将Bean的名字(id)赋值给变量。
ApplicationContextAware
实现该类可以获取到ApplicationContext,通过ApplicationContext就可以获取到Bean
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null){
SpringUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
EmbeddedValueResolverAware
通过实现该类就可以获取到spring核心配置文件中的配置值(application.yml,application.properties)。
但是需要通过${key}获取
/**
* 非spring容器管理的类可以通过此类获取配置值
*/
@Component
public class PropertiesUtil implements EmbeddedValueResolverAware {
private static StringValueResolver resolver;
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
PropertiesUtil.resolver = resolver;
}
public static String getPropertiesValue(String key){
return resolver.resolveStringValue(key);
}
}
举例:
String name = PropertiesUtil.getPropertiesValue("${spring.application.name}")