Spring注解驱动开发实战 | 第十五篇:自动装配-Aware注入Spring底层组件

自定义组件实现xxxAware,就可以使用Spring容器底层的一些组件(ApplicationContext,BeanFactory等),
在创建对象的时候,会调用接口规定的方法注入相关组件;
 

在com.wsc.bean中创建Red.java并实现ApplicationContextAware,BeanNameAware,EmbeddedValueResolverAware等

package com.wsc.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

    @Component
	public class Red implements ApplicationContextAware,BeanNameAware,EmbeddedValueResolverAware {
		
		private ApplicationContext applicationContext;

		
		public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
			
			System.out.println("传入的ioc:"+applicationContext);
			this.applicationContext = applicationContext;
		}

		
		public void setBeanName(String name) {
			
			System.out.println("当前bean的名字:"+name);
		}

		
		public void setEmbeddedValueResolver(StringValueResolver resolver) {
		
			String resolveStringValue = resolver.resolveStringValue("你好 ${os.name} 我是 #{20*18}");
			System.out.println("解析的字符串:"+resolveStringValue);
		}

}

在MainConifgOfAutowired.java中添加注解@ComponentScan扫描到这个bean

package com.wsc.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.wsc.bean.Car;
import com.wsc.bean.Color;
import com.wsc.dao.PersonDao;

@Configuration
@ComponentScan({"com.wsc.servicer","com.wsc.dao",
	"com.wsc.controller","com.wsc.bean"})
public class MainConifgOfAutowired {
	
	@Primary
	@Bean("personDao2")
	public PersonDao personDao(){
		PersonDao personDao = new PersonDao();
		personDao.setLable("2");
		return personDao;
	}
	
	/**
	 * @Bean标注的方法创建对象的时候,方法参数的值从容器中获取
	 * @param car
	 * @return
	 */
	@Bean
	public Color color(Car car){
		Color color = new Color();
		color.setCar(car);
		return color;
	}
	
}
	

在IOCTest_Autowired.java中添加测试方法testAware

@Test
	public void testAware(){
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConifgOfAutowired.class);
		
		applicationContext.close();
	}

运行测试方法,查看使用Spring容器底层的一些组件所获得的信息:

--------------------------------

源码下载

 

你可能感兴趣的:(spring注解,Spring注解驱动开发实战)