结论: Aware接口的实现是依赖于BeanPostProcessor接口
示例:
创建一个RedisAware接口,此接口继承Aware接口,具体如下
import org.springframework.beans.factory.Aware;
public interface RedisAware extends Aware {
void setRedis(String redis);
}
创建一个RedisAware接口的实现类
import org.springframework.stereotype.Component;
@Component
public class MyRedisAware implements RedisAware {
private String redis;
@Override
public void setRedis(String redis) {
// TODO Auto-generated method stub
this.redis = redis;
System.out.println("-----MyRedisAware----" + redis);
}
}
创建一个用来处理RedisAware类型接口的BeanPostProcessor
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class RedisAwareProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RedisAware) {
System.out.println("-----RedisAwareProcessor-----");
((RedisAware) bean).setRedis("myRedis");
}
return bean;
}
}
至此,就能实现,MyRedisAware类中redis属性的自动赋值
要点还是,BeanPostProcessor的使用,完全可以不用Aware接口,可以自定义一个接口(AAA),
然后在BeanPostPorcessor中检测bean是否实现了AAA接口即可对实现了AAA接口的类的属性进行制动赋值的功能