1

我有一个具有以下属性的控制器:

@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 吗?

非常感谢您的建议!

亲切的问候,

4

1 回答 1

2

您可以只使用 JSF,甚至 CDI 集成也可以帮助您将其划分为适当的层。看看这个 JSF 解决方案,它使用了一个管理配置的应用程序范围的 bean。的范围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,它读取您想要的文件并存储一个带有读取值的标志。我使用一个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 表达式(请参阅参考资料)。

也可以看看:

于 2014-03-17T16:10:52.787 回答