name |
---|
ApplicationContextAware |
ApplicationEventPublisherAware |
BeanClassLoaderAware |
BeanFactoryAware |
BeanNameAware |
BootstrapContextAware |
LoadTimeWeaverAware |
MessageSourceAware |
NotificationPublisherAware |
ResourceLoaderAware |
ServletConfigAware |
ServletContextAware |
该文章简单介绍一个Aware接口。其他的Aware都非常的类似,之不过是Spring传入的是不同的对象。如果还想了解其他的Aware对象请查看Api文档。
1.ApplicationContextAware
以下为ApplicationContextAware接口以及其中定义的方法
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
如果我们的Bean实现了ApplicationContextAware接口,那么Spring会将ApplicationContext对象的引用传递到我们的Bean中。有时这种方式是有用的,但是在一般的开发中应该避免使用该方式,因为这种方式会导致将Spring代码耦合到我们自己的应用程序中。这并不符合Spring提到的非侵入特性性。
请看以下的代码:
首先创建了一个Person类并且实现了ApplicationContextAware接口
package pojo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 该类实现了ApplicationContextAware,在实例化该类时,Spring会将ApplicationContext的引用传递到该类内部
* @author Administrator
*/
public class Person implements ApplicationContextAware {
public void setApplicationContext(ApplicationContext context)
throws BeansException {
// TODO Auto-generated method stub
System.out.println("TestAwareService -> setApplicationContext");
System.out.println(context);
}
}
接下在XML中配置Bean
<bean name="person" class="pojo.Person"></bean>
最后,创建测试方法进行测试
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
context.getBean("person") ;
System.out.println("Main -> main");
System.out.println(context);
/**
* 可以看到运行结果中context是同一个对象,这就说明Spring将context对象传递进了Person实例中
*/
}
}
运行结果:输出的两次context对象的引用是同一个这就说明Spring为实现了ApplicationContextAware的Bean传入了context对象的引用。