关于 Spring 的 Aware 接口

一、Spring所提供的Aware接口:

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

BeanFactoryAware:在Bean中得到Bean所在的IOC容器

ApplicationContextAware:在Bean中得到Bean所在的应用上下文

MessageSourceAware:在Bean中可以得到消息源

ApplicationEventPublisherAware:在bean中可以得到应用上下文的事件发布器

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

二、以BeanNameAware、ApplicationContextAware接口举例说明:

<bean id ="myContext" class="com.jsun.test.springDemo.aware.MyApplicationContext"></bean>
//实现BeanNameAware接口,并重写setBeanName()方法,让Bean获取自己在BeanFactory配置中的名字(id或name)
//实现ApplicationContextAware接口,并重写setApplicationContext()方法
public class MyApplicationContext implements BeanNameAware,ApplicationContextAware{
    private String beanName;

    //注入的beanName即为MyApplicationContext在BeanFactory配置中的名字(根据情况是id或者name)
    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
        System.out.println("MyApplicationContext beanName:"+beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        //通过重写的接口方法,获取spring容器实例context,进而获取容器中相关bean资源
        System.out.println(context.getBean(this.beanName).hashCode());

    }

}

猜你喜欢

转载自blog.csdn.net/eaphyy/article/details/79274517