簡體   English   中英

使用ManagedProperty有條件地注入bean

[英]Conditional injection of bean with ManagedProperty

我有一個具有以下屬性的控制器:

@ManagedProperty(value="#{remoteApplication}")
private transient ProcessService applicationService;

@ManagedProperty(value="#{remoteSystem}")
private transient SystemService systemService;

@ManagedProperty(value="#{remoteFileSystem}")
private transient FileSystemService fileSystemService;

根據一個屬性文件,我想有條件地注入bean,該文件告訴服務是本地的還是遠程的。

上面提供的示例是針對遠程的,對於本地而言的是:

@ManagedProperty(value="#{localApplication}")
private transient ProcessService applicationService;

@ManagedProperty(value="#{localSystem}")
private transient SystemService systemService;

@ManagedProperty(value="#{localFileSystem}")
private transient FileSystemService fileSystemService;

有什么方法可以用JSF做到這一點(也許使用ManagedProperty文檔中指定的ValueExpression )? 還是我必須使用CDI?

預先非常感謝您的建議!

親切的問候,

以星

您可以只使用JSF做到這一點,即使CDI集成也可以幫助您將其划分為適當的層。 使用管理配置的應用程序范圍的Bean,看看這個JSF解決方案。 Bean的范圍可以是您需要的任何人。 作為您的服務類@ManagedBean

@ManagedBean
@ApplicationScoped
public class LocalProcessService implements ProcessService {

    public LocalProcessService() {
        System.out.println("Local service created");
    }

}

@ManagedBean
@ApplicationScoped
public class RemoteProcessService implements ProcessService {

    public RemoteProcessService() {
        System.out.println("Remote service created");
    }

}

然后,實現一個配置Bean,該Bean讀取所需的文件並存儲帶有讀取值的標志。 我使用Random函數進行測試:

@ManagedBean(eager = true)
@ApplicationScoped
public class PropertiesBean {

    private boolean localConfig = false;

    public PropertiesBean() {
        // Read your config file here and determine wether it is local
        //or remote configuration
        if (new Random().nextInt(2) == 1) {
            localConfig = true;
        }
    }

    public boolean isLocalConfig() {
        return localConfig;
    }

}

一旦獲得,在您的視圖控制器中使用三元運算符根據該標志值進行注入:

@ManagedBean
@ViewScoped
public class Bean {

    @ManagedProperty(value = "#{propertiesBean.localConfig ? localProcessService : remoteProcessService}")
    protected ProcessService processService;

    public void setProcessService(ProcessService processService) {
        this.processService = processService;
    }

}

或者,您可以將服務引用直接存儲在PropertiesBean ,以便不必在托管bean中評估該標志值。 只需在上下文中評估所需的EL表達式即可(請參閱參考資料)。

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM