基於泛型的自動裝配
泛型自動裝配例子:
public interface Store<T> {
}
public class IntegerStore implements Store<Integer> {
}
public class StringStore implements Store<String> {
}
package com.torey.beanannotation.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 IntegerStore s2(){
return new IntegerStore();
}
@Bean
public StringStore s1(){
StringStore ss=new StringStore();
System.out.println("StringStore:"+ss.hashCode());
return ss;
}
@Bean
public Store stringStoreTest(){
System.out.println("s1:" + s1.getClass().getName()+";s1.hashCode:"+s1.hashCode());
System.out.println("s2:" + s2.getClass().getName());
StringStore ss= new StringStore();
System.out.println("stringStoreTest:"+ss.hashCode());
return ss;
}
}
package com.torey.springtest.base;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
public class UnitTestBase {
public UnitTestBase(){}
private String springXmlPath;
private ClassPathXmlApplicationContext applicationContext;
public UnitTestBase(String springXmlpath){
this.springXmlPath=springXmlpath;
}
@Before
public void before(){
if (StringUtils.isEmpty(springXmlPath)) {
springXmlPath="classpath*:spring-*.xml";
}
applicationContext= new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]"));
applicationContext.start();
}
@After
public void after(){
applicationContext.destroy();
}
public Object getBean(String beanId){
return applicationContext.getBean(beanId);
}
}
package com.torey.springtest.bean;
import com.torey.beanannotation.javabased.Store;
import com.torey.springtest.base.UnitTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase {
public TestBeanAnnotation(){
super("classpath:spring-beanannotation.xml");
}
@Test
public void testG(){
Store store=(Store) super.getBean("stringStoreTest");
}
}
Autowire擴展:自定義qualifier註解
CustomAutowireConfigurer
- CustomAutowireConfigurer是BeanFactoryPostProcessor的子類,通過它可以註冊自己的qualifier註解類型(即使沒有使用Spring的@Qualifier註解)
<bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
<property name="customQualifierTypes">
<set>
<value>example.CustomQualifier</value>
</set>
</property>
</bean>
- 該AutowireCandidateResolver決定自動裝配的候選者:
- 每個bean定義的autowire-candidate值
- 任何< bean/ >中的default-autowire-candidates
- @Qualifier註解及使用CustomAutowireConfigurer的自定義類型
根據慕課網 moocer老師的spring課程 整理