Spring学習(16)---Javaクラスに基づく構成Beanの汎用ベースの自動アセンブリ(spring 4新規)
3391 ワード
例:
汎用Storeの定義
2つの実装クラスStringStore、IntegerStore
JAva config bean構成の実装
XML構成:
ユニットテスト:
結果:
参考にもなります(詳しくは):http://blog.csdn.net/yangxt/article/details/19970323
汎用Storeの定義
package javabased;
public interface Store<T> {
}
2つの実装クラス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