Example:
Defining a generic Store
Package Javabased;public interface Store<t> {}
Two implementation Classes Stringstore,integerstore
Package Javabased;public class Integerstore implements store<integer> {}
Package Javabased;public class Stringstore implements store<string> {}
Java Config implements bean configuration
Package Javabased;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;@ Configurationpublic class Storeconfig {@Autowiredprivate store<string> s1; @Autowiredprivate Store<integer > s2, @Beanpublic stringstore Stringstore () {return new Stringstore (); @Beanpublic Integerstore Integerstore () {return new Integerstore ();} @Bean (name= "test_generic") public String print () { //test System.out.println ("S1:" +s1.getclass (). GetName ()); System.out.println ("S2:" +s2.getclass (). GetName ()); return "";}}
XML configuration:
<?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>
Unit tests:
Package Javabased;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class UnitTest {@Testpublic void Test () { ApplicationContext context = new Classpathxmlapplicationcontext ("Classpath:spring-beanannotation.xml"); Context.getbean ("Test_generic");}}
Results:
2015-7-8 15:12:04 org.springframework.context.support.ClassPathXmlApplicationContext Preparerefresh Info: Refreshing Org[email protected]32bf7190:startup Date [Wed Jul 15:12:04 CST 2015]; Root of context hierarchy2015-7-8 15:12:04 Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions info: Loading XML Bean Definitions from class path resource [spring-beanannotation.xml]s1:javabased. Stringstores2:javabased. Integerstore
can also refer to (very detailed): http://blog.csdn.net/yangxt/article/details/19970323
Spring Learning (+)---generic-based automatic assembly of Java class-based configuration beans (Spring4 new)