What makes a bean a CDI bean?

笑着哭i 提交于 2019-12-06 13:43:15

问题


In the top answer to this question for example : Java EE 6 @javax.annotation.ManagedBean vs. @javax.inject.Named vs. @javax.faces.ManagedBean I read that:

To deploy CDI beans, you must place a file called beans.xml in a META-INF folder on the classpath. Once you do this, then every bean in the package becomes a CDI bean.

And also it is said that:

If you want to use the CDI bean from a JSF page, you can give it a name using the javax.inject.Named annotation.

I have a sample code that goes like this:

@ManagedBean
@ViewScoped
public class SignUpPage {

    private User user;

    @PostConstruct
    public void init() {
        user = new User();
    }

    @Inject
    private UserDao userDao;
// rest of the class

So as far as I understand, my bean is still a JSF Managed Bean, it is not a CDI bean(or is it?). By the way, I have a beans.xml in my WEB-INF folder.

And @Inject works just fine in here. Also, I can access the bean with EL just fine(which makes me think it is still a JSF Managed Bean)

The UserDao class looks something like this:

@Stateless
public class UserDao {
    EntityManager em;
    @PostConstruct
    public void initialize(){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Persistence");
        em = emf.createEntityManager();
    }

So, it is as far as I know an EJB..

So do I have any CDI beans in this example? How does @Inject work here?

Hope my question is clear, Regards!


回答1:


By CDI specification, every JavaBean is a Managed Bean (do not confuse it with JSF @ManagedBean, this is a different one) in project where the beans.xml is present. So every class is also eligible for dependency injection. Note that default scope of this class is Dependent.



来源:https://stackoverflow.com/questions/18579963/what-makes-a-bean-a-cdi-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!