【发布时间】:2012-11-25 06:30:01
【问题描述】:
使用 Guice,可以执行以下操作:
interface Leg {}
_
class LeftLeg implements Leg {
public String toString() {
return "LeftLeg";
}
}
_
class RightLeg implements Leg {
public String toString() {
return "RightLeg";
}
}
_
class Robot {
final Leg leftLeg_;
final Leg rightLeg_;
@Inject
Robot(@Named("left") Leg leftLeg, @Named("right") Leg rightLeg) {
leftLeg_ = leftLeg;
rightLeg_ = rightLeg;
}
public String toString() {
return "leftLeg_=" + leftLeg_ + ", rightLeg_=" + rightLeg_;
}
}
_
class RobotTest {
@Test
public void t1() throws Exception {
Injector inj = Guice.createInjector(new AnGuiceModule());
Robot r = inj.getInstance(Robot.class);
assertEquals(r.toString(), "leftLeg_=LeftLeg, rightLeg_=RightLeg");
}
}
_
class AnGuiceModule extends AbstractModule {
protected void configure() {
bind(Leg.class).annotatedWith(Names.named("left")).to(LeftLeg.class);
bind(Leg.class).annotatedWith(Names.named("right")).to(RightLeg.class);
}
}
如何在 Spring 3.x(3.1.x 或 3.2)中使用 JSR-330(可选)注解和 JavaConfig,而不使用 XML 配置来实现相同的功能?
【问题讨论】:
标签: java spring dependency-injection ioc-container guice