【问题标题】:Conditional injection of bean with ManagedProperty使用 ManagedProperty 条件注入 bean
【发布时间】:2014-03-17 15:53:17
【问题描述】:

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

@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 做到这一点(也许使用 ValueExpression 中指定的 ManagedProperty documentation)?或者我必须使用 CDI 吗?

非常感谢您的建议!

亲切的问候,

Zim

【问题讨论】:

    标签: jsf cdi managed-property


    【解决方案1】:

    您可以只使用 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 表达式(请参阅参考资料)。

    另请参阅:

    【讨论】:

    • 我很惭愧没有想到这么明显......非常感谢@Xtremebiker!
    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2011-07-07
    • 2012-02-14
    • 2011-07-07
    • 2012-11-14
    • 2013-10-01
    • 2011-11-24
    • 2011-12-16
    相关资源
    最近更新 更多