Spring实现Aware接口,完成对IOC容器的感知

容器管理的Bean一般不需要了解容器的状态和直接使用容器,但是在某些情况下,是需要在Bean中直接对IOC容器进行操作的,这时候,就需要在Bean中设定对容器的感知。Spring IOC容器也提供了该功能,它是通过特定的Aware接口来完成的。aware接口有以下这些:

BeanNameAware,可以在Bean中得到它在IOC容器中的Bean的实例的名字。

BeanFactoryAware,可以在Bean中得到Bean所在的IOC容器,从而直接在Bean中使用IOC容器的服务。

ApplicationContextAware,可以在Bean中得到Bean所在的应用上下文,从而直接在Bean中使用上下文的服务。

MessageSourceAware,在Bean中可以得到消息源。

ApplicationEventPublisherAware,在bean中可以得到应用上下文的事件发布器,从而可以在Bean中发布应用上下文的事件。

ResourceLoaderAware,在Bean中可以得到ResourceLoader,从而在bean中使用ResourceLoader加载外部对应的Resource资源。

在设置Bean的属性之后,调用初始化回调方法之前,Spring会调用aware接口中的setter方法。

下面给出一个例子:

定义一个实现BeanNameAware接口的类:

package com.spring.aware;

import org.springframework.beans.factory.BeanNameAware;

/**
 * 

Class:LoggingBean

*

Description:

* @author Liam * @Date [2012-9-7 上午9:23:12] */ public class LoggingBean implements BeanNameAware { private String name; public void setBeanName(String name) { this.name = name; } public void run() { System.out.println("容器被感知--BeanNameAware:Bean name is'" + this.name + "'.>>"+name); } }

在定义个实现BeanFactoryAware接口的类:

package com.spring.aware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

/**
 * 

Class:ShutdownHookBean

*

Description:

* @author Liam * @Date [2012-9-7 上午9:24:13] */ public class BeanDestried implements BeanFactoryAware{ private ConfigurableListableBeanFactory beanFactory; public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof DefaultListableBeanFactory) { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } } public void run() { if (this.beanFactory != null) { System.out.println("容器被感知--BeanFactory-Destroying singletons.>>"+beanFactory); this.beanFactory.destroySingletons(); } } }

在applicationContext中配置好:


测试类如下:

package com.spring.aware;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 

Class:App

*

Description:

* @author Liam * @Date [2012-9-7 上午9:13:36] */ public class App { public static void main(String[] args) throws Exception { ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:beans.xml"); LoggingBean lb = (LoggingBean) factory.getBean("logging"); lb.run(); BeanDestried sd = (BeanDestried)factory.getBean("beanDestried"); sd.run(); } }

测试结果如下:

容器被感知--BeanNameAware:Bean name is'logging'.>>logging
容器被感知--BeanFactory-Destroying singletons.>>org.springframework.beans.factory.support.DefaultListableBeanFactory@a6cdf5: defining beans [logging,beanDestried]; root of factory hierarchy

你可能感兴趣的:(Spring实现Aware接口,完成对IOC容器的感知)