目录
1、概述
Spring 提供了一些 Aware接口,比如BeanFactoryAware、ApplicationContextAware、ResourceLoaderAware等,实现Aware接口的bean在被初始化之后,可以取得一些相对应的资源。例如BeanFactoryAware 在 bean 初始化后,Spring容器将会注入 BeanFactory 的实例。
2、BeanFactoryAware 示例
创建普通类
package thinking.in.spring.boot.samples.spring5.aware;
public class Hello {
public void say() {
System.out.println("hello aware");
}
}
创建BeanFactoryAware
package thinking.in.spring.boot.samples.spring5.aware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class HelloAware implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void testHelloAware() {
Hello hello = (Hello) this.beanFactory.getBean("hello");
hello.say();
}
}
spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:customLabel="http://www.rh.com/schema/customLabel"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.rh.com/schema/customLabel
http://www.rh.com/schema/customLabel.xsd">
<bean id="hello" class="thinking.in.spring.boot.samples.spring5.aware.Hello" />
<bean id="helloAware" class="thinking.in.spring.boot.samples.spring5.aware.HelloAware" />
</beans>
spring引导类
package thinking.in.spring.boot.samples.spring5.bootstrap;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import thinking.in.spring.boot.samples.spring5.aware.HelloAware;
import thinking.in.spring.boot.samples.spring5.circle.CircleA;
import thinking.in.spring.boot.samples.spring5.circle.CircleB;
import thinking.in.spring.boot.samples.spring5.circle.CircleC;
public class AwareBootstrap {
public static void main(String[] args) {
DefaultListableBeanFactory defaultListableBeanFactory = new XmlBeanFactory(new ClassPathResource("application-aware.xml"));
HelloAware helloAware = (HelloAware)defaultListableBeanFactory.getBean("helloAware");
helloAware.testHelloAware();
}
}
运行结果
信息: Loading XML bean definitions from class path resource [application-aware.xml]
hello aware