JSF 2 inject Spring bean/service with @ManagedProperty and no xml
Solution 1:
If you already have Spring container why not use its @Autowired annotation. For that, Update your faces-config.xml as suggested by Boni. Then add these listeners to your web.xml after this
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
Then add these to your applicationContext.xml
<context:component-scan base-package="com.examples" />
Now you can use Spring annotations and your bean will be something like this:
package com.examples;
@Component
@Scope(value="request")
public class MyBean {
@Autowired
private MySpringBeanClass mySpringBean;
}
Annotate your MySpringBeanClass with @Service
See Also:
- @Scope("request") not working
Solution 2:
Put this code in your faces-config.xml
<faces-config 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/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
Then in your ManageBean Constructor call;
WebApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
mySpringBean = ctx.getBean(MySpringBean.class);
MySpringBean mean your Spring Bean Class
Solution 3:
Assuming you have configured Spring properly in web.xml and applicationContext.xml. Make the following entry in faces-config.xml
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
Your sample code given above seems fine. What will happen with above entry is Managed Property will be first looked in beans managed by JSF if not found will be searched in beans managed by Spring. Your spring bean should have proper annotations marked and name given in @ManagedProperty should match with default/name given to bean.
As mentioned by @Boni that is not required it is auto injected. I have used settings as you desire.
A side note: Since you are opting for view scope please have a look at this link The benefits and pitfalls of @ViewScoped