要想在自定义组件中获取spring底层的各种组件,只需让自定义组件实现一系列接口即可,这些接口都是Aware的子接口。常见的有:
1. ApplicationContextAware——用于获取IOC容器;
2. BeanNameAware——用于获取bean的名称;
3. EmbeddedValueResolverAware——用于获取字符串解析器,可以解析各种占位符,例如${}、$#{}等。
示例代码如下,自定义bean类实现了三种Aware接口
public class Candy implements ApplicationContextAware, BeanNameAware, EmbeddedValueResolverAware { //bean的名称 private String name; //容器 private ApplicationContext applicationContext; //配置文件中的值 private String nickname; @Override public void setBeanName(String name) { this.name = name; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.nickname = resolver.resolveStringValue("${bottle.nickname}"); } }