4

I'm using decorator pattern in java ee 7 (glassfish 4).

I've 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, EntityManager in EJB is null (without decorator, everything goes fine). I supose is because of decorator use @Inject instead of @EJB annotation (@EJB annotation can't be used in @Decorator), and EntityManager is not being injected.

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

Thank you

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • You're mixing concepts. [`@Decorator` comes from CDI managed beans](http://docs.oracle.com/javaee/6/tutorial/doc/gkhqf.html) while `@EJB` is for EJB injection. – Luiggi Mendoza Jun 20 '13 at 15:11
  • So, Luiggi Mendoza, repeat my cuestion. What can I do to get entitymanager will be injected using @decorator with this code? – Miguel Ángel Júlvez Jun 20 '13 at 15:56
  • @LuiggiMendoza According to the CDI 1.1 specification an EJB is also a managed bean. See section [3.1.1. Which Java classes are managed beans?](http://docs.jboss.org/cdi/spec/1.1/cdi-spec.html#what_classes_are_beans) of the CDI 1.1 spec. – Oliver Sep 09 '13 at 12:33
  • Yes they are, but CDI and EJB beans are handled by different managers. – Luiggi Mendoza Sep 09 '13 at 14:13

1 Answers1

0

Try adding an empty beans.xml in your META-INF, this will activate CDI bean discovery. I had a similar issue 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 indicate to GlassFish Server that your application is a CDI application. This file can 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

sashok_bg
  • 2,436
  • 1
  • 22
  • 33