Spirng Aware接口实现

来源:互联网 发布:java微信开发框架对比 编辑:程序博客网 时间:2024/05/19 13:29


1 引

    Spring提供了很多以Aware结尾的接口,我们可以通过类实现接口和接口中要实现的方法,获取Spring资源。

    大致过程:在使用Bean的时候,Spring会首先判断该Bean是否实现了Aware接口,如果实现了,在Spring初始化Bean的时候就会通过函数回调而调用Bean对象对Aware接口的实现方法,获取相应资源。

    (如何理解回调函数,见Java回调函数机制

    总之,通过Aware接口,可以对Spring相应资源进行操作,但是一定要操作要慎重。这种机制给Spring进行简单的扩展提供了入口,方便又实用。


     Aware提供的一系列接口          

  1.           ApplicationContextAware
  2.           ApplicationEventPublishAware
  3.           BeanClassLoaderAware
  4.           BeanFactoryAware
  5.           BeanNameAware
  6.           BeanstrapContextAware
  7.           LoadTimeWeaverAware
  8.           MessageSourceAware
  9.           NotaficationPublishAware
  10.           PortletConfigAware
  11.           PortletContextAware
  12.           ResourceLoaderAware


2 ApplicationContextAware接口实现示例

1 示例

下面说一个Spring下对Aware具体的应用例子:

###### 实现类TerenceApplicationContext 

            (实现ApplicationContextAware接口):

public class TerenceApplicationContext implements ApplicationContextAware {private ApplicationContext applicationContext;public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {  this.applicationContext=applicationContext;      System.out.println("TAContext:"+applicationContext.getBean("terenceApplicationContext"));}public void a(){System.out.println(applicationContext.hashCode());}}

###### 配置文件spring-aware.xml:

<?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="terenceApplicationContext" class="com.terence.aware.TerenceApplicationContext"></bean> </beans>

##### 测试类TestAware

@RunWith(BlockJUnit4ClassRunner.class)public class TestAware extends UnitTestBase {public TestAware(){super("classpath*:spring-aware.xml");}@Testpublic void testTerenceApplicationContext(){System.out.println("tAC Bean的定义:"+super.getBean("terenceApplicationContext"));}}

####测试结果:



2 结果分析

    整体执行流程:在测试类中,通过super.getBean(“……”),调用父类UnitTestBased函数的getBean方法,通过上下文,在配置文件spring-aware.xml文件中找到对应的实现类并初始化,得到一个实例对象Bean。

     第一行TAContext:com.terence.aware.TerenceApplicationContext@11e86299

     表示通过配置文件得到的接口的实现类terenceApplicationContext,经过函数回调执行了接口实现类中的实现方法setApplication()得到的Bean定义的上下问名称。

     第二行tAC Bean的定义:com.terence.aware.TerenceApplicationContext@11e86299

     表示的是测试类中打印出来的方法Bean对象定义类的上下文名称,参见整体执行流程。

 


0 1