spring aware

ApplicationContextAware-将ApplicationContextAware注入到bean中

package com.imooc.aware;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class MoocApplicationContext implements ApplicationContextAware  {
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		System.out.println("MoocApplicationContext : " +
				applicationContext.getBean("moocApplicationContext").hashCode());
	}
	
}

通过applicationContext.getBean(“moocApplicationContext”)得到的bean信息是与super.getBean()方式一样的。

BeanNameAware-将XML中配置的bean的名字注入到类中

package com.imooc.aware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class MoocBeanName implements BeanNameAware, ApplicationContextAware {

	private String beanName;
	
	@Override
	public void setBeanName(String name) {
		this.beanName = name;
		System.out.println("MoocBeanName : " + name);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		System.out.println("setApplicationContext : " + applicationContext.getBean(this.beanName).hashCode());
	}

}

通过实现BeanNameAware接口,拿到bean的名字,然后通过ApplicationContextAware接口

实现拿到该bean实例。

测试方法

package com.imooc.test.aware;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.imooc.test.base.UnitTestBase;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestAware extends UnitTestBase {
	
	public TestAware() {
		super("classpath:spring-aware.xml");
	}
	
//	@Test
//	public void testMoocApplicationContext() {
//		System.out.println("testMoocApplicationContext : " + 
               super.getBean("moocApplicationContext").hashCode());
//	}
	
	@Test
	public void textMoocBeanName() {
		System.out.println("textMoocBeanName : " + super.getBean("moocBeanName").hashCode());
	}
        // super.getBean()是在完成bean的初始化之后进行的操作,所以会比两个接口的注入更晚
	
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部