gpt4 book ai didi

java - 在没有范围注释的情况下,由 @Produces 方法创建的 bean 的默认范围是什么?

转载 作者:行者123 更新时间:2023-12-02 02:17:51 24 4
gpt4 key购买 nike

我有一个带有 @Produces 的方法创建 Apple 的注释。

当我像这样与 @ApplicationScoped 一起使用时

public class AppleProducer {
@ApplicationScoped
@Produces
public Apple createApple() {
return new Apple();
}
}

然后 Apple 只为整个应用程序创建一次。

当我像这样将它与 @RequestScoped 一起使用时

public class AppleProducer {
@RequestScoped
@Produces
public Apple createApple() {
return new Apple();
}
}

然后为每个请求创建它。

但是如果我不指定范围怎么办?

public class AppleProducer {
@Produces
public Apple createApple() {
return new Apple();
}
}

苹果多久会被创建一次?我每次访问都怀疑,这是正确的吗?有相关文档吗?

最佳答案

这是 @Dependent

根据2.4.4. Default scope中的“CDI (1.2) specification” :

When no scope is explicitly declared by annotating the bean class or producer method or field the scope of a bean is defaulted.

The default scope for a bean which does not explicitly declare a scope depends upon its declared stereotypes:

• If the bean does not declare any stereotype with a declared default scope, the default scope for the bean is @Dependent.

• If all stereotypes declared by the bean that have some declared default scope have the same default scope, then that scope is the default scope for the bean.

• If there are two different stereotypes declared by the bean that declare different default scopes, then there is no default scope and the bean must explicitly declare a scope. If it does not explicitly declare a scope, the container automatically detects the problem and treats it as a definition error.

If a bean explicitly declares a scope, any default scopes declared by stereotypes are ignored.

关于java - 在没有范围注释的情况下,由 @Produces 方法创建的 bean 的默认范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com