如何在类构造函数运行之前使用 EJB 3.1 注入 Bean?
我有一个带有持久性单元的外观。我需要在 RoleController 构造函数运行之前初始化 Facade 及其依赖项,在 EJB 3.1 中可以这样做吗?
在 Spring 中,您只需向 @configurable 添加一些参数 (preConstruction="true") 即可。
但在 EJB 中我找不到一种方法来做到这一点,我总是得到一个 NullPointer...
@FacesConverter("rolesConverter")
@Named("roleController")
@SessionScoped
@TransactionManagement(TransactionManagementType.CONTAINER)
public class RoleController implements Serializable, Converter{
private List<Roles> listOfRoles;
private List<Roles> listChoosenRoles;
private DualListModel<Roles> listOfDualRoles;
@EJB
private RoleFacade roleFacade;
public RoleController(){
listOfRoles = roleFacade.getListOfRoles();
listChoosenRoles = new ArrayList();
listOfDualRoles = new DualListModel<Roles>(listOfRoles, listChoosenRoles);
}
I have a Facade that has a persistence unit. And I need the Facade and it's dependencies initialized before the RoleController Conconstructor runs, is it possible in EJB 3.1 to do that ?
In Spring you simple add some parameters (preConstruction="true") to the @configurable and it's done.
But in EJB I cannot find a way to do that I always get a NullPointer...
@FacesConverter("rolesConverter")
@Named("roleController")
@SessionScoped
@TransactionManagement(TransactionManagementType.CONTAINER)
public class RoleController implements Serializable, Converter{
private List<Roles> listOfRoles;
private List<Roles> listChoosenRoles;
private DualListModel<Roles> listOfDualRoles;
@EJB
private RoleFacade roleFacade;
public RoleController(){
listOfRoles = roleFacade.getListOfRoles();
listChoosenRoles = new ArrayList();
listOfDualRoles = new DualListModel<Roles>(listOfRoles, listChoosenRoles);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在构造函数中执行任何逻辑通常是一个坏主意(不仅在 EJB 游乐场上)。使用
@PostConstruct
相反:使用此注释,容器将首先实例化一个 EJB 对象,JVM 运行一个(空)构造函数,容器通过反射注入依赖项,当一切准备就绪时,在未指定的情况下调用所有用
@PostConstruct
注释的方法 命令。现在 EJB 已准备好服务请求。我认为某些容器/较新的 EJB 规范允许构造函数注入,但我从未使用过它。
It is generally a bad idea to perform any logic in the constructor (not only on EJB playground). Use
@PostConstruct
instead:With this annotation the container will first instantiate an EJB object, JVM runs an (empty) constructor, container via reflection injects dependencies and when everything is ready calls all methods annotated with
@PostConstruct
in unspecified order. Now the EJB is ready to serve requests.I think some containers/newer EJB spec allows constructor injection, but I have never used it.