我正在学习Java、依赖注入,特别是@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();
}
}
}发布于 2014-09-12 04:54:29
我想知道为什么在getGreedingCard()方法中,它需要一个@Produces注释,因为GreetingCardImpl和AnotherGreetingCardImpl两个类已经导入到了空间中。
嗯,并不是getGreetingCard需要@Produces注释。关键是使其他类能够通过依赖项注入接收GreetingCards。
public class Foo {
@Inject // <--- will invoke @Producer method
GreetingCard foosGreetingCard
...
}有关更多细节,请参见这里:
生产者方法是充当bean实例源的方法。方法声明本身描述bean,当指定的上下文中不存在实例时,容器调用该方法来获取bean的实例。
发布于 2014-09-12 08:51:05
在您的示例中,它不需要@Produces,因为您将注入工厂bean并使用其方法直接创建实例,而不是注入greetingCard bean。
@Inject
GreetingCardFactory factory;
...
GreetingCard card = factory.getGreetingCard();如果将其定义为@Produces方法,并尝试注入GreetingCard,那么您将得到我在注释中描述的异常。
但是,如果要另外创建限定符,如下所示:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
public @interface ProducedCard {}并将其添加到producer方法中:
@Produces @ProducedCard
public GreetingCard getGreetingCard() {
...然后,您就可以使用如下的生产者方法只注入GreetingCard bean:
@Inject @ProducedCard
GreetingCard card;由于现在没有歧义,因为只有一个地方可以创建标记为@ProducedCard的贺卡:-)
https://stackoverflow.com/questions/25800828
复制相似问题