1、创建自定义注解
1 import org.springframework.beans.factory.annotation.Qualifier; 2 import java.lang.annotation.ElementType; 3 import java.lang.annotation.Retention; 4 import java.lang.annotation.RetentionPolicy; 5 import java.lang.annotation.Target; 6 7 8 @Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE}) 9 @Retention(RetentionPolicy.RUNTIME) 10 @Qualifier 11 public @interface StringedInstrument { 12 13 }
Retention注解有一个属性value,是RetentionPolicy类型的,Enum RetentionPolicy是一个枚举类型,
用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;
用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时,
2、创建instrument ,并使用注解
1 @StringedInstrument 2 public class Instrument { 3 4 public void play() { 5 System.out.println("playing..."); 6 } 7 }
3、创建表演者kenny,进行自动装配
1 import org.springframework.beans.factory.annotation.Autowired; 2 3 public class Kenny { 4 5 @Autowired 6 @StringedInstrument 7 private Instrument instrument; 8 9 public Instrument getInstrument() { 10 return instrument; 11 } 12 13 public void setInstrument(Instrument instrument) { 14 this.instrument = instrument; 15 } 16 17 18 public Kenny(Instrument instrument) { 19 this.instrument = instrument; 20 } 21 22 public void perform(){ 23 instrument.play(); 24 } 25 }
4、配置spring
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 6 7 <context:annotation-config></context:annotation-config> 8 9 <bean id="kenny" class="Kenny"> 10 </bean> 11 12 <bean id="instrument" class="Instrument"> 13 14 </bean> 15 16 </beans>
5、测试
1 import org.springframework.context.ApplicationContext; 2 import org.springframework.context.support.ClassPathXmlApplicationContext; 3 4 5 public class Test { 6 public static void main(String[] args) { 7 8 ApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); 9 Kenny kenny = (Kenny) context.getBean("kenny"); 10 kenny.perform(); 11 } 12 }