Spring4.0学习笔记 第二章 自动装配(使用自定义的限定符注解)

来源:互联网 发布:照片美发软件 编辑:程序博客网 时间:2024/06/04 18:35

Spring4.0允许我们使用自定义的限定注解,现在我们有一个Disk接口,两个实现类JayDiskImpl 和TomDiskImpl,现在我们要在CtBean中自动注入Disk 的实例,因为有两个实现类,使用@Autowired 是会报错的(没有加限定符注解的话,注入的实例默认只能有一个实现,大于一个会报错),如果我们不自己实现可以使用@Autowired @Qualifier("jayDiskImpl"),或者@Autowired @Qualifier("tomDiskImpl") 或者@Resource(name="jayDiskImpl") 这些都能帮我们精确定位到具体要注入哪一个接口的实现

bean。。 那如何通过自己定义的注解来具体定位到我们所需要的bean实例


以下是简单的测试例子

目录:

JavaConfig

package test;import org.springframework.context.annotation.ComponentScan;import org.springframework.stereotype.Component;@ComponentScan@Componentpublic class JavaConfig {}
Disk:

package test;public interface Disk {void play();}

JayDiskImpl:

package test;import org.springframework.stereotype.Component;import soundsystem.DiskInterface;@Component@Jaypublic class JayDiskImpl implements DiskInterface, Disk {public void play() {System.out.println("cd 1");}}
TomDiskImpl:

package test;import org.springframework.stereotype.Component;@Component@Tom //这个地方一定要加这个自定义注解(类似于spring框架的@Qualifier相当于给这个bean指定具体//的名字),换句话说相当于给当前bean指定名称以便注入引用它,类似@Component("xx")或者 //@Component @Qualifier("xx")(这两个注解合起来用等价于==@Component("xx"))public class TomDiskImpl implements Disk {public void play() {System.out.println("cd 2");}}
Jay:

package test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.beans.factory.annotation.Qualifier;@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documented@Qualifierpublic @interface Jay {}
Tom:

package test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.beans.factory.annotation.Qualifier;@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documented@Qualifier//通过在定义时添加@Qualifier注解,它们就具有了@Qualifier注解的特性。//它们本身实际上就成为了限定符注解。public @interface Tom {//Tom这个自定义注解,相当于是换了我们自己要的名字的@Qualifier注解}

CtBean:

package test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class CtBean {@Autowired@Tomprivate Disk di;public void testAno(){di.play();}}

Test:

package test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext ac =new AnnotationConfigApplicationContext(JavaConfig.class);CtBean ct=ac.getBean("ctBean", CtBean.class);ct.testAno();}}


输出:cd 2


0 0
原创粉丝点击