码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-08 16:25:20      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

例子:

定义泛型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

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

标签:

原文地址:http://www.cnblogs.com/JsonShare/p/4629511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!