@Autowired service inside a @ManagedBean @Component class is null during JSF request [duplicate]

旧时模样 提交于 2019-12-01 17:56:00

Both JSF and Spring can act as bean containers. The @ManagedBean annotation instructs the JSF managed bean facility to create a new instance of the class, and manage it under the given name. The @Component annotation instructs the Spring ApplicationContext to create a new instance of the class, and manage it under the given name. That is, both JSF and Spring create an instance of that class, the JSF one is reachable through EL, but the Spring one gets its dependencies injected (because, being a spring annotation, @Autowired is not understood by the JSF managed bean facility).

So you have a choice: Use the JSF managed bean facility for everything (which I would not recommend, as it is rather limited), use CDI for everything (which is an option, but does not use Spring), or use Spring for everything (which I usually do), by removing the @ManagedBean annotation, and making Spring beans accessible through EL by registering a SpringBeanFacesELResolver in your faces-config.xml. The Spring reference manual describes this in section 19.3.1.

I had the same issue, it was due to the property name of @ManagedBean annotation.My backing bean looks like this

@Component
@ManagedBean(name="mainBean")
@SessionScoped
public class MainManagedBean{...}

As you can see, the name given to the bean (mainBean) is different to the default name (mainManagedBean) that the backing bean should have.

I have fixed the issue by setting the property name to "mainManagedBean". My bean becomes like this:

@Component
@ManagedBean(name="mainManagedBean")
@SessionScoped
public class MainManagedBean{...}

I wish this can help you

I believe the reason why testService is null is because testService has not been instantiated yet when managed bean is being constructed. So you can use @PostConstruct to inject Spring beans into a managed bean.

@ManagedBean(name = "userBean")
@Scope
@Component
public class someBean {

    @Autowired
    private TestService testService;

    public void printString() {
        System.out.println(testService.getString());
    }

    @PostConstruct
    private void init() {
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        ServletContext servletContext = (ServletContext) externalContext.getContext();
    WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).
                                   getAutowireCapableBeanFactory().
                                   autowireBean(this);
    }
}

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