我正在学习Java EE CDI,依赖注入,@Produces
尤其是。我很奇怪,为什么在getGreedingCard()
方法,它需要@Produces
在所有的注释,因为这两个类GreetingCardImpl
,并AnotherGreetingCardImpl
已导入的空间。就像常规的包/类依赖项一样,简单的导入即可解决问题。为什么它需要通过@producer
注释进行依赖项注入?
感谢您事先的解释。
public interface GreetingCard {
void sayHello();
}
public class GreetingCardImpl implements GreetingCard {
public void sayHello() {
System.out.println("Hello!!!");
}
}
public class AnotherGreetingCardImpl implements GreetingCard {
public void sayHello() {
System.out.println("Have a nice day!!!");
}
}
import com.javacodegeeks.snippets.enterprise.cdibeans.impl.AnotherGreetingCardImpl;
import com.javacodegeeks.snippets.enterprise.cdibeans.impl.GreetingCardImpl;
@SessionScoped
public class GreetingCardFactory implements Serializable {
private GreetingType greetingType;
@Produces
public GreetingCard getGreetingCard() {
switch (greetingType) {
case HELLO:
return new GreetingCardImpl();
case ANOTHER_HI:
return new AnotherGreetingCardImpl();
default:
return new GreetingCardImpl();
}
}
}
我想知道为什么在getGreedingCard()方法中,它根本就需要@Produces批注,因为两个类GreetingCardImpl和AnotherGreetingCardImpl已经导入到空间中了。
好吧,这并不是说getGreetingCard需要@Produces批注。关键是使其他类能够通过依赖注入来接收GreetingCard。
public class Foo {
@Inject // <--- will invoke @Producer method
GreetingCard foosGreetingCard
...
}
请参阅此处以获取更多详细信息:
生产者方法是充当Bean实例源的方法。方法声明本身描述了bean,并且在指定的上下文中不存在任何实例时,容器将调用该方法以获取bean的实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句