从Bean中获取到的容器实例并对其进行操作。
public interface Aware {
}
该接口只能当做是一个顶级接口使用,主要依赖于其下的子接口:
BeanFactoryAware 就是用于获取BeanFactory相关的信息。
ResourceLoaderAware 就是用于获取ResourceLoader相关信息。
…
以此类推。
故在以上子接口中,均包含一个setter方法。什么意思呢?
例如,当前有个Controller类需要获取ApplicationContext这个Bean,那么这个Controller类可继承ApplicationContextAware接口,通过实现setter方法来获取到ApplicationContext实例。
@Controller
public class DemoController implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public void hello() {
System.out.println(context);
}
}
此外,当然可以同时实现多个接口获得多个想要得到的Bean,例如:
@Controller
public class DemoController implements ApplicationContextAware, BeanNameAware {
private ApplicationContext context;
private String myName;
@Autowired
private DemoService demoService;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public void setBeanName(String name) {
this.myName = name;
}
public void hello() {
demoService.hello("来自Controller的问候");
System.out.println("我是:" + myName);
// 获取容器中所有的Bean
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println(myName + "获取到:" + name);
}
}
}
执行结果:
来自Controller的问候
我是:demoController
demoController获取到:org.springframework.context.annotation.internalConfigurationAnnotationProcessor
demoController获取到:org.springframework.context.annotation.internalAutowiredAnnotationProcessor
demoController获取到:org.springframework.context.annotation.internalCommonAnnotationProcessor
demoController获取到:org.springframework.context.event.internalEventListenerProcessor
demoController获取到:org.springframework.context.event.internalEventListenerFactory
demoController获取到:application
demoController获取到:customizedBeanDefinitionPostProcessor
demoController获取到:customizedBeanPostProcessor
demoController获取到:demoController
demoController获取到:demoServiceImpl
demoController获取到:user5