使用装饰器时未注入 SessionContext

SessionContext not injected when using decorators

我正在使用 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 没有被注入。

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

public class Producers {

    @Produces
    @Resource
    private SessionContext em;
}

然后在装饰器中使用 @Inject 注释而不是 @Resource。这也不行。

有什么方法可以在装饰器中使用 @Resource 或做类似的事情吗?

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