[英]@Autowired JSF 2 Spring 3 Null
I am not able to inject the service using the @Autowired. 我无法使用@Autowired注入服务。
AplicationContext.xml AplicationContext.xml
<context:component-scan base-package="com.mypackage" />
<context:component-scan base-package="com.mypackage.bean" />
<context:component-scan base-package="com.mypackage.dao" />
<context:component-scan base-package="com.mypackage.service" />
<context:component-scan base-package="com.mypackage.filters" />
<context:annotation-config />
faces-config.xml faces-config.xml中
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver></application>
web.xml web.xml中
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Service declaration: 服务声明:
@Service
public class UsuarioServiceImpl extends GenericServiceImpl implements UsuarioService{...}
ManagedBean: ManagedBean:
@ManagedBean(name="cadastroUsuarioMB")
@SessionScoped
public class CadastroUsuarioBean {
@Autowired
UsuarioService usuarioService;
private Usuario usuario = new Usuario();
public String salvar() {
//Error !!! usuarioService is null !
usuarioService.retornaUsuarioPorLogin(usuario.getEmail(), usuario.getSenha());
JsfUtil.addSuccessMessage(null, usuario.getCelular());
return "";
}
}
That error is because UsuarioService is spring context managed bean and @ManagedBean is jsf managed bean. 该错误是因为UsuarioService是spring上下文管理的bean,而@ManagedBean是jsf管理的bean。 Either 1)replace @ManagedBean with @Component to make @Autowire inject the service or 2) 1)用@Component替换@ManagedBean以使@Autowire注入服务,或2)
@ManagedProperty(value="#{usuarioService}")
private UsuarioService usuarioService ; // mutators for this.
}
In your configuration file AplicationContext.xml 在您的配置文件AplicationContext.xml中
<context:component-scan base-package="com.mypackage.bean" />
Need to put the annotation " @Controller " on your Bean 需要在您的Bean上添加注释“ @Controller ”
@Controller
@ManagedBean(name="cadastroUsuarioMB")
@SessionScoped
public class CadastroUsuarioBean {
@Autowired
UsuarioService usuarioService;
private Usuario usuario = new Usuario();
public String salvar() {
//Error !!! usuarioService is null !
usuarioService.retornaUsuarioPorLogin(usuario.getEmail(), usuario.getSenha());
JsfUtil.addSuccessMessage(null, usuario.getCelular());
return "";
}
}
If you want to inject your service by using Spring, So you have to change the declaration in the above of your controller. 如果要使用Spring注入服务 ,则必须在控制器的上面更改声明。
replace @ManagedBean(name="cadastroUsuarioMB")
by @Component("cadastroUsuarioMB")
like this you inform Spring container to manage the injection and not JSF container. 像这样用@Component("cadastroUsuarioMB")
替换@ManagedBean(name="cadastroUsuarioMB")
,您可以通知Spring容器管理注入而不是JSF容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.