在我的例子中,我有一个“英雄”bean,它可以被注入一个“武器”bean。英雄和武器都是原型范围的(我们可以有多个英雄,他们不会共享武器)。
我想要的是一个名为“勇士”的英雄配置,它被注入了一把“剑”武器,而一个名为“弓箭手”的英雄配置被注入了一个“弓”武器。然后在我的申请中我会打电话给
context.getBean("Warrior");每次我都想找个新战士。
我知道如何用XML来完成这个任务,但是我想知道是否可以用注释来完成这个任务?如果是的话,我该如何做?我正在使用Spring 4。
发布于 2014-10-23 18:04:12
LuiggiMendoza的评论示例(自动引导和限定设置者)
坚持编程脚本到接口,我们有Hero接口
public interface Hero {
void killOrBeKilled();
}我们还将有一个AbstractHero抽象类来组合一些常见的功能。注意,我们没有实现setWeapon方法。我们会把这个留给混凝土班的。
public abstract class AbstractHero implements Hero {
protected Weapon weapon;
public void killOrBeKilled() {
weapon.secretWeaponManeuver();
}
protected abstract void setWeapon(Weapon weapon);
}这是我们将要使用的限定符。注意,您不必创建自己的限定符。您可以简单地使用@Qualifer("qualifierName")进行匹配。我这么做只是因为我可以:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface BowType { }
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface SwordType { }对于Warrior,我们将使用@SwordType限定符
@Component
public class Warrior extends AbstractHero {
@SwordType
@Autowired
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
}对于Archer,我们将使用@BowType限定符
@Component
public class Archer extends AbstractHero {
@BowType
@Autowired
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
}在我们的Weapons具体类中,我们还需要用适当的限定符对类进行注释
public interface Weapon {
void secretWeaponManeuver();
}
@BowType
@Component
public class Bow implements Weapon {
public void secretWeaponManeuver() {
System.out.println("Bow goes Slinnnggggg!");
}
}
@SwordType
@Component
public class Sword implements Weapon {
public void secretWeaponManeuver() {
System.out.println("Sword goes Slassshhhh!");
}
}当我们运行应用程序时,将根据我们的限定符正确地注入武器类型。
@Configuration
@ComponentScan(basePackages = {"com.stackoverflow.spring.hero"})
public class Config { }
public class Application {
public static void main(String[] args) {
AbstractApplicationContext context =
new AnnotationConfigApplicationContext(Config.class);
Hero warrior = context.getBean(Warrior.class);
warrior.killOrBeKilled();
Hero archer = context.getBean(Archer.class);
archer.killOrBeKilled();
context.close();
}
}结果
剑去斯拉斯什哈! 鞠躬,斯林尼格!
我忘了@Scope("prototype")注释了。
https://stackoverflow.com/questions/26532473
复制相似问题