Java EE 7 - @Decorator, @Stateless and @PersistenceContext = nullpointerException

I am using a decorator pattern in java ee 7 (glassfish 4).

I have this decorator

@Decorator public class FooIndexer implements FooService { @Inject @Delegate FooService fooService; private Logger logger = Logger.getLogger(FooIndexer.class.getName()); //@Inject //Indexer indexer; @Override public Foo create(Foo foo, boolean index) { fooService.create(foo, index); if (index) { System.out.println("Im in"); } return foo; } 

}

And this ejb class

 @Stateless(name = "fooService") @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @DeclareRoles({"ADMINISTRATOR", "USER"}) public class FooServiceImpl implements FooService { @PersistenceContext(unitName = "foo") private EntityManager em; @Resource(lookup="java:comp/EJBContext") private SessionContext ctx; /** CRUD **/ @RolesAllowed("ADMINISTRATOR") public Foo create(Foo foo, boolean index) { Principal cp = ctx.getCallerPrincipal(); System.out.println(cp.getName()); em.persist(foo); return foo; } } 

When I use this decorator pattern, the EntityManager in EJB is null (everything works fine without a decorator). I believe that using the @Inject decorator instead of the @EJB annotation (@EJB annotation cannot be used in @Decorator), and EntityManager is not introduced.

But, what can I do to get entitymanager to be injected using @decorator?

thanks

+4
source share
1 answer

Try adding an empty beans.xml file to your META-INF, this will activate CDI bean detection. I had a similar problem with my project.

See oracle doc here: http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html

You must create an empty beans.xml file to tell the GlassFish server that your application is a CDI application. This file may have content in some situations, but not in simple applications like this one.

http://docs.oracle.com/javaee/6/tutorial/doc/gjbju.html#gjcvh

Good luck

Alexander Kirilov

0
source

Source: https://habr.com/ru/post/1487318/


All Articles