users@glassfish.java.net

_at_Inject + _at_ManagedBean vs _at_EJB

From: Dominik Dorn <dominik.dorn_at_gmail.com>
Date: Wed, 16 Dec 2009 23:28:46 +0100

Hi,

I want my app to be portable with other frameworks (mainly spring 3.0) and
thought
it would be possible to replace the @EJB annotations with @Inject, but
nope.. that does not work..

whats wrong with lets say, this bean? :

@ManagedBean
@ApplicationScoped
public class MemberListService {

    @Inject
    private PersonDao personDao;

    public MemberListService() {
    }

    public List<Person> findAll() {
        return personDao.findAll();
    }

    public void persist(Person person) {
        personDao.persist(person);
    }


}

and the bean accessing the service

@ManagedBean
@RequestScoped
public class MemberListBean {
    private Logger log = Logger.getLogger(MemberListBean.class);

    private List<Person> memberList;

    public List<Person> getMemberList() {
        return memberList;
    }

    public void setMemberList(List<Person> memberList) {
        this.memberList = memberList;
    }

    @Inject
    private MemberListService service;

    public MemberListService getService() {
        return service;
    }

    public void setService(MemberListService service) {
        this.service = service;
    }

    public MemberListBean() {

    }

    @PostConstruct
    void loadData() {
        System.out.println("calling postConstruct");

        log.debug("calling postConstruct");
        if (service != null) {
            System.out.println("loading personDao.findAll()");
            setMemberList(service.findAll());
            System.out.println("loaded data");
        }
        else
        {
            log.warn("PersonDAO is null!");
        }
        log.debug("poluted memberList");
        log.debug("memberlist now has " + memberList.size() + " items");
    }


}


when using @Inject instead of @EJB, the loadData() method throws a NPE,
because service is null, althought it should be injected.

I have created an empty beans.xml in my /WEB-INF/ dir, as explained in "The
Java EE 6 Tutorial Volume 1"

What am I doing wrong?

Greetings,
Dominik