【问题标题】:SessionContext not injected when using decorators使用装饰器时未注入 SessionContext
【发布时间】:2015-02-25 08:07:16
【问题描述】:

我正在使用 Glassfish 4 部署应用程序。它曾经有一个 EJB,其中 SessionContext 通过@Resource 注解注入。

@Stateless
@DeclareRoles({"StandardRole1", "StandardRole2"})
public class MyClass implements MyInterface {

    @Resource
    private SessionContext ctx;

    @Override
    public String getPrincipalName() {
        return ctx.getPrincipal().getName();
    }
}

这工作正常。现在我需要获得额外的允许角色来扩展应用程序。新角色并不总是相同的,因此无法将角色添加到 MyClass bean。我想出的是这样的:

@Stateless
@DeclareRoles({"StandardRole1", "StandardRole2"})
public class NormalRoles implements RolesInterface {

    @Resource
    private SessionContext ctx;

    @Override
    public String getPrincipalName() {
        return ctx.getPrincipal().getName();
    }
}

@Decorator
@DeclareRoles({"NewRole1", "NewRole2"})
public abstract NewRoles implements RolesInterface {

    @Inject
    @Delegate
    @Default
    private RolesInterface defaultBean;

    @Resource
    private SessionContext ctx;

    @Override
    public String getPrincipalName() {
        return ctx.getPrincipal().getName();
    }
}

@Stateless
public class MyClass implements MyInterface {

    @Inject
    private RolesInterface rolesBean;

    @Override
    public String getPrincipalName() {
        return rolesBean.getPrincipalName();
    }
}

现在,当我尝试运行它时,我从 NewRoles 装饰器获得了 return ctx.getPrincipal().getName(); 上的 NullPointerException。问题 --> SessionContext 没有被注入。

我之前在here 发布的 PersistenceContext 中遇到过这个问题。我试图以这种方式解决它,所以做这样的事情:

public class Producers {

    @Produces
    @Resource
    private SessionContext em;
}

然后在装饰器中使用@Inject 注解代替@Resource。这也不起作用。

有没有办法可以在装饰器中使用@Resource 或做类似的事情?

【问题讨论】:

    标签: java jakarta-ee glassfish ejb cdi


    【解决方案1】:

    SessionContext 是链接到 EJB 的资源,而装饰器不是 EJB,而是 CDI bean,因此您得到一个空的 SessionContext 是正常的。 您可以尝试通过 Jndi 获取 SessionContext,如下所述:http://javahowto.blogspot.fr/2006/06/4-ways-to-get-ejbcontext-in-ejb-3.html

    【讨论】:

    • 我已经尝试了最后 3 种可能性,都未能获得 SessionContext。我现在从这个问题中了解到,我需要在 CDI bean 中有一个 EJB 资源。但到目前为止,我似乎无法得到它。
    • 不知道为什么第一次没有用,但我重试了几次,第三次后,我让它与 JNDI "java:comp/EJBContext" 一起工作"
    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2022-07-21
    • 2018-08-07
    相关资源
    最近更新 更多