Spring Aware接口
BeanNameAware接口
BeanNameAware接口提供setBeanName()方法,实现这个接口可以返回我们当前的beanName属性。
public class SimpleBeanNameAware implements BeanNameAware {
private String beanName;
@Override
public void setBeanName(String name) {
this.beanName = name;
System.out.println("beanName:" + this.beanName);
}
}
@Configuration
public class AppConfig {
@Bean
public SimpleBeanNameAware simpleBeanNameAware(){
return new SimpleBeanNameAware();
}
}
public class AppMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.close();
}
}
beanName:simpleBeanNameAware
BeanFactoryAware接口
当类实现BeanFactoryAware接口,就有了一个BeanFactory的引用,通过这个BeanFactory的引用,我们可以获取容器中创建的对象。
public class SimpleBeanFactoryAware implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
}
@Configuration
public class AppConfig {
@Bean
public SimpleBeanFactoryAware simpleBeanFactoryAware(){
return new SimpleBeanFactoryAware();
}
@Bean
public Person person(){
Person person = new Person();
person.setName("xiyangyang");
return person;
}
}
public class AppMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Person person = context.getBean(SimpleBeanFactoryAware.class).getBeanFactory().getBean(Person.class);
System.out.println(person);
context.close();
}
}
初始化Person
Person{name='xiyangyang', age=null, sex='null'}
ApplicationContextAware接口
通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法,可以通过这个上下文环境对象得到Spring容器中的Bean
public class ApplicationContextHolder implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
@Configuration
public class AppConfig {
@Bean
public ApplicationContextHolder applicationContextHolder(){
return new ApplicationContextHolder();
}
@Bean
public Person person(){
Person person = new Person();
person.setName("xiyangyang");
return person;
}
}
public class AppMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Person person = context.getBean(ApplicationContextHolder.class).getApplicationContext().getBean(Person.class);
System.out.println(person);
context.close();
}
}
初始化Person
Person{name='xiyangyang', age=null, sex='null'}