除了使用Qualifier注释器,还可以使用自定义相关的限定器。使用自定义注释器时,要以Qualifier注释作为他的元注解。
如下面的例子:
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface PonitPerson {
}
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface PonitPerson {
}
上面的代码自定了一个PointPerson限定器,相关的工程结构如下图所示。其中Person是一个接口,BlackMan与YelloMan实现了该接口,
代码如下:
package Bena;
@PonitPerson
public class BlackMan implements Person{
public String address="African";
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
要在WorldPerson里面注入一个Person类的Bean,其中BlackMan与YelloMan都可以进行相关的匹配,为了能够指明要匹配的Bean,在BlackMan内使用自定义的注释。然后WorldPerson代码如下:
@PonitPerson
public class BlackMan implements Person{
public String address="African";
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
要在WorldPerson里面注入一个Person类的Bean,其中BlackMan与YelloMan都可以进行相关的匹配,为了能够指明要匹配的Bean,在BlackMan内使用自定义的注释。然后WorldPerson代码如下:
package Bena;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class WorldPerson {
@Autowired
@PonitPerson
public Person person;//此时会注入的Bean是所有匹配的Bean中标记注释为PonitPerson的Bean,即BlackMan
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class WorldPerson {
@Autowired
@PonitPerson
public Person person;//此时会注入的Bean是所有匹配的Bean中标记注释为PonitPerson的Bean,即BlackMan
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
测试代码如下:
package Main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Bena.WorldPerson;
public class MainClass {
public static void main(String[]args)
{
ApplicationContext context=new ClassPathXmlApplicationContext("Bean.xml");
WorldPerson man=(WorldPerson)context.getBean("worldMan");
System.out.println(man.person.toString());
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Bena.WorldPerson;
public class MainClass {
public static void main(String[]args)
{
ApplicationContext context=new ClassPathXmlApplicationContext("Bean.xml");
WorldPerson man=(WorldPerson)context.getBean("worldMan");
System.out.println(man.person.toString());
}
}
输出:Bena.BlackMan@10b40af
整个demo源码已经附上:
http://download.csdn.net/detail/muyundefeng/9477971