Aware接口:
常见的Aware:
- ApplicationContextAware:向实现了这个接口的bean提供ApplicationContext(IOC容器的上下文信息),实现了这个接口的bean必须配置到Spring的bean配置文件中去,并且由Spring的bean容器去加载。
- BeanNameAware:提供一个关于BeanName的定义的内容。
- ApplicationEventPublisherAware:事件的发布
- BeanClassLoaderAware:找到相关的类加载器
例:
spring-aware.xml创建两个bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id="moocApplicationContext" class="com.aware.MoocApplicationContext"></bean>
<bean id="moocBeanName" class="com.aware.MoocBeanName"></bean>
</beans>
MoocApplicationContext.java:
package com.aware;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MoocApplicationContext implements ApplicationContextAware{
//可以进行声明
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) //参数applicationContext是加载了这个bean的IOC容器的上下文信息
throws BeansException {
this.applicationContext=applicationContext;
//在applicationContext中获取bean的实例
System.out.println("MoocApplicationContext:"+applicationContext.getBean("moocApplicationContext").hashCode()); //判断是不是同一个bean
}
}
MoocBeanName.java:
package com.aware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MoocBeanName implements BeanNameAware,ApplicationContextAware { //同时实现BeanNameAware,ApplicationContextAware
private String beanName;
@Override
public void setBeanName(String name) {
this.beanName=name;
System.out.println("MoocBeanName:"+name); //name的值就是在配置文件中bean的id
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
//根据bean名称从applicationContext中得到相应的bean的实例
System.out.println("setApplicationContext:"+applicationContext.getBean(this.beanName).hashCode());
}
}
测试类TestAware:
package com.test.aware;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.imooc.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAware extends UnitTestBase {
public TestAware() {
super("classpath:spring-aware.xml");
}
@Test
public void testMoocApplicationContext(){
//从IOC容器中得到bean的实例
System.out.println("testMoocApplicationContext:"+super.getBean("moocApplicationContext").hashCode());
}
@Test
public void testMoocBeanName(){
System.out.println("testMoocBeanName:"+super.getBean("moocBeanName").hashCode()); //通过id来得到bean的实例
}
}
运行测试方法testMoocApplicationContext:
运行testMoocBeanName: