1. 程式人生 > >spring中aware接口的

spring中aware接口的

ram 對象 直接 loader number source clas spring servlet

一、關於spring中Aware結尾接口介紹:

Spring中提供一些Aware結尾相關接口,像是BeanFactoryAware、 BeanNameAware、ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等。

實現這些 Aware接口的Bean在被實例化
之後,可以取得一些相對應的資源,例如實現BeanFactoryAware的Bean在實例化後,Spring容器將會註入BeanFactory的實例,而實現ApplicationContextAware的Bean,在Bean被實例化後,將會被註入 ApplicationContext的實例等等。

通過重寫setter方法,當前bean被實例化後實現相關實例的註入。

二、以BeanNameAware、ApplicationContextAware接口舉例說明:

<bean name ="myContext" class="com.jsun.test.springDemo.aware.MyApplicationContext"></bean>
  • 1
//實現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());

    }

}
    @Test
    public void testScope(){
        //單元測試再次獲取bean,並輸出bean的hashCode
        System.out.println(super.getBean("myContext").hashCode());
    }

上面輸出結果:

信息: Loading XML bean definitions from URL [file:/E:/workspace/springDemo/target/classes/spring-ioc.xml]
MyApplicationContext beanName:myContext
1663216960
1663216960
八月 07, 2016 4:25:12 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@5531a519: startup date [Sun Aug 07 16:25:11 CST 2016]; root of context hierarchy

註意:除了通過實現Aware結尾接口獲取spring內置對象,也可以通過@Autowired註解直接註入相關對象,如下:
(如果需要用到靜態方法中,如工具方法,還是采用實現接口的方式)

@Autowired
private MessageSource messageSource; 

@Autowired
private ResourceLoader resourceLoader; 

@Autowired
private ApplicationContext applicationContext;

spring中aware接口的