ApplicationScoped

@ApplicationScoped
public class ApplicationScopedClass {
    //This class gets constructed once for the entire life of the application, and is shared among all CDI-managed classes throughout the life of the application.

    @Inject
    public ApplicationScopedClass(SomeDependency someDependency) {
        doSomethingWith(someDependency);
    }

    public ApplicationScopedClass() {
        //Note that it is required that an application scoped class have a public no-args constructor
    }

}

具有 @ApplicationScoped 的類只建立一次,並且依賴於該類的每個物件共享同一個例項。這些類是有效的單例,但應該注意的是,沒有什麼可以阻止編碼人員手動建立該類的其他例項。因此,使用 @ApplicationScoped 對於在整個應用程式中共享上下文非常有用,或者作為效能優化(如果構造例項的類很昂貴),但不應該依賴它作為保證僅一個例項的完整性度量。類存在。

與請求範圍的 bean 一樣,應用程式範圍的 bean 需要有一個公共的無引數建構函式。