在JSF请求期间,@ ManagedBean @Component类中的@Autowired服务为null

Dmi*_*ich 5 spring dependency-injection jsf-2 managed-bean

我尝试使用JSF 2进行联合Spring 3(MVC).我在Spring和JSF中有一些经验,但之前从未尝试过加入它们.最后我有2个文件

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

  @Autowired
  private TestService testService;

  public void printString() {
    System.out.println(testService.getString());
  }
}
Run Code Online (Sandbox Code Playgroud)

@ManagedBean(name = "studentBean")
@Scope
@Component
public class StudentBean {

  @Autowired
  private TestService testService;

  public void printString() {
    System.out.println(testService.getString());
  }
}
Run Code Online (Sandbox Code Playgroud)

对于这些文件,我有正确的spring,jsf和web.xml配置.并有.xhtml页面,我为'someBean'和'StudentBean'启动printString().我在第一种情况下使用NPE,在第二种情况下在控制台中使用"some string".原因很简单 - Spring上下文和JSF中的bean名称不同.所有问题都完成了

@Component => @Component("userBean") 
public class someBean {
Run Code Online (Sandbox Code Playgroud)

在调试中我看到了

private TestService testService;

@Autowired
public void setTestService(TestService testservice) {
  this.testService = testService;
}
Run Code Online (Sandbox Code Playgroud)

当JSF bean创建的testService集不为null时,但在JSF生命周期中它为null时

public void pringString() {
  testService.blah();
}
Run Code Online (Sandbox Code Playgroud)

testService为null.这是我无法理解的.有谁深入了解Spring和JSF详细描述这种情况?

mer*_*ike 10

JSF和Spring都可以充当bean容器.该@ManagedBean注释指示JSF托管bean工具来创建类的新实例,和给定的名义对其进行管理.该@Component注释指导Spring的ApplicationContext创建类的新实例,和给定的名义对其进行管理.也就是说,JSF和Spring都创建了该类的实例,JSF可以通过EL访问,但是Spring会注入其依赖项(因为,作为一个spring注释,@ Autowired不被JSF托管bean工具理解) .

所以你有一个选择:将JSF托管bean工具用于所有东西(我不推荐,因为它相当有限),使用CDI进行一切(这是一个选项,但不使用Spring),或者使用Spring进行一切(我通常这样做),通过删除@ManagedBean注释,并通过SpringBeanFacesELResolver在faces-config.xml中注册一个来通过EL访问Spring bean .Spring参考手册在第19.3.1节中对此进行了描述.