How to inject a CDI Bean in a ManagedBean?

后端 未结 3 1825
我在风中等你
我在风中等你 2021-01-02 23:12

I want to inject a CDI Bean in a ManagedBean either with the annotation @Inject or @Produce. The CDI Bean which I use is:

@Named
@Startup
@ApplicationScoped
         


        
相关标签:
3条回答
  • 2021-01-02 23:26

    What @patlov is suggesting will work if you use @Named on your CDI beans. However, if you're working in an environment that supports CDI, do not use @ManagedBean. Instead, use CDI all the way. See this answer and I'm sure you could find numerous other ones that strongly advise against what you're trying to do.

    Just switch from javax.faces.bean.SessionScoped to javax.enterprise.context.SessionScoped and everything will magically work. What you may run into is the absense of @ViewScoped from CDI however, in which case use something like JBoss Seam or Apache Deltaspike that implement it for you. As an added benefit, they will also automatically replace all of the JSF scopes with CDI scopes automatically if you already have existing code written for JSF.

    Update: This should be the content of your beans.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    </beans>
    
    0 讨论(0)
  • 2021-01-02 23:31

    If you are using @ManagedBean use @ManagedProperty to inject properties:

    @ManagedProperty(value = "#{baseBean}")
    private BaseBean dBean;
    
    // getter and setter
    
    0 讨论(0)
  • 2021-01-02 23:45

    Make sure you have enabled CDI by putting a WEB-INF/beans.xml file in your application.

    0 讨论(0)
提交回复
热议问题