spring中aware接口的

一、关于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;

猜你喜欢

转载自www.cnblogs.com/stevehu1231/p/9393546.html