@Produces方法创建的没有范围注释的bean的默认范围是什么? [英] What's the default scope for a bean created by a @Produces method without a scope annotation?

查看:79
本文介绍了@Produces方法创建的没有范围注释的bean的默认范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 @Produces 注释创建一个 Apple

当我将它与 @ApplicationScoped 一起使用

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

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

then the Apple gets created only once for the whole application.

当我将其与 @RequestScoped 一起使用时

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

然后为每个请求创建它。

then it gets created for every request.

但是如果我不指定范围呢?

But what if I do not specify a scope?

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

苹果将多久创建一次?我怀疑每次访问都正确吗?

How often will the Apple be created? I suspect on every access, is it correct? Is there documentation about this?

推荐答案

它是 @ Dependent

根据 2.4.4。默认范围 ,来自 CDI(1.2)规范


在没有通过注释bean明确声明范围的情况下类或
生产者方法或字段Bean的范围是默认范围。

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

未显式声明范围
的Bean的默认范围。取决于其已声明的构造型:

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

•如果Bean未声明具有已声明的默认
范围的任何构造型,则该Bean的默认范围为@Dependent。

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

•如果bean声明的所有具有
默认作用域的构造型都具有相同的默认作用域,则该作用域为
默认作用域

• 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.

•如果有两个不同Bean声明的nt原型,
声明了不同的默认范围,那么就没有默认范围,并且
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.

如果已明确指定Bean声明作用域,将忽略
构造型声明的任何默认作用域。

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

这篇关于@Produces方法创建的没有范围注释的bean的默认范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆