天天看點

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注解驅動開發實戰 | 第十五篇:自動裝配-Aware注入Spring底層元件源碼下載下傳

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

源碼下載下傳

繼續閱讀