Spring学习(16)--- 基于Java类的配置Bean 之 基于泛型的自动装配(spring4新增)

例子:

定义泛型Store

package javabased;

public interface Store<T> {

}

 两个实现类StringStore,IntegerStore

package javabased;

public class IntegerStore implements Store<Integer> {

}

 

package javabased;

public class StringStore implements Store<String> {
	
}

 java config实现bean配置

package javabased;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StoreConfig {
	
	@Autowired
	private Store<String> s1;
	
	@Autowired
	private Store<Integer> s2;
	
	@Bean
	public StringStore stringStore() {
		return new StringStore();
	}
	
	@Bean
	public IntegerStore integerStore() {
		return new IntegerStore();
	}
	
	@Bean(name="test_generic")
	public String print(){    //测试
		System.out.println("s1 : "+s1.getClass().getName());
		System.out.println("s2 : "+s2.getClass().getName());
		return "";
	}
	
}

XML配置:

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
        
        <context:component-scan base-package="javabased">
        </context:component-scan> 
        
</beans>

 单元测试:

package javabased;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class UnitTest {
	
	@Test
	public void test(){
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beanannotation.xml");  
		context.getBean("test_generic");
		
	}
}

 结果:

2015-7-8 15:12:04 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32bf7190: startup date [Wed Jul 08 15:12:04 CST 2015]; root of context hierarchy
2015-7-8 15:12:04 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-beanannotation.xml]
s1 : javabased.StringStore
s2 : javabased.IntegerStore

 

也可参考(挺详细的):http://blog.csdn.net/yangxt/article/details/19970323

 

posted @ 2015-07-08 15:20  Json_wangqiang  阅读(886)  评论(0编辑  收藏  举报