[英]EJB update bean property at runtime
我有一個包含一些 web 客戶端實現的 bean,它可以是 REST 或 SOAP:
@Stateless
public class Service{
private Client client;
@PostConstruct
public void init() {
this.client = new RESTClient();
}
}
有沒有辦法可以更新“客戶端”,例如在 JSF controller 中,並且此更改在整個應用程序的上下文中持續存在?
@ViewScoped
@ManagedBean
public class ServiceController {
@EJB
private Service service;
public void updateClient() {
// code to update the client
// Service.client = new SOAPClient();
}
}
根據您的評論,如果您的堆棧中有 CDI,我建議您使用它。
CDI 具有許多功能,您可以使用這些功能來准確地完成您想要做的事情:Alternative 似乎最適合您的用例,但您還應該檢查 Qualifiers、Decorators 和 Specializes/Stereotypes。
這里有一個參考: https://docs.jboss.org/weld/reference/latest/en-US/html/specialization.html
@RequestScoped
public class RESTClient
implements Service {
...
}
@Alternative @RequestScoped
public class SoapClient
implements Service {
...
}
@ViewScoped
@ManagedBean
public class ServiceController {
@Inject private Service service;
}
然后,您可以在運行時在 beans.xml 中交換活動替代項:
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
<alternatives>
<class>org.mycompany.myapp.SoapClient</class>
</alternatives>
</beans>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.