一、自定义注解:
package cn.edu.tju.anno;import java.lang.annotation.*;@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyQualifier {String value() default "";
}
二、定义bean,使用自定义注解;
package cn.edu.tju.anno;import cn.edu.tju.domain.MovieCatalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class MovieRecommender2 {@Autowired@MyQualifier("thrill")public MovieCatalog movieCatalog;// ...
}
三、配置文件中配置CustomAutowireConfigurer
<?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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="cn.edu.tju.anno"/><bean class="cn.edu.tju.domain.SimpleMovieCatalog"><qualifier type="cn.edu.tju.anno.MyQualifier" value="thrill"/></bean><bean id="customAutowireConfigurer"class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer"><property name="customQualifierTypes"><set><value>cn.edu.tju.anno.MyQualifier</value></set></property></bean></beans>
四、主类
package cn.edu.tju;import cn.edu.tju.anno.MovieRecommender;
import cn.edu.tju.anno.MovieRecommender2;
import cn.edu.tju.study.service.anno.domain.MyValueCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Start19 {public static void main(String[] args) {ApplicationContext applicationContext = newClassPathXmlApplicationContext("beans19.xml");MovieRecommender2 bean = applicationContext.getBean(MovieRecommender2.class);System.out.println(bean.movieCatalog);}
}