I am just starting using JSF and I don’t understand why my service is not injected into my controller.
@ManagedBean
@ApplicationScoped
public class MyController {
@ManagedProperty(value = "#{service}")
private MyService service;
public void setService(MyService service) {
this.service = service;
}
public MyService getService() {
return service;
}
public void callToService(AjaxBehaviorEvent event) {
System.out.println(service);
}
}
Q: What is the purpose of the value in the @ManagedProperty?
@ManagedBean
@ApplicationScoped
public class MyService {
}
Clicking on the button calls the method callToService but the service is null.
<h:form>
<h:commandButton value="Call Service">
<f:ajax listener="#{myController.callToService}"/>
</h:commandButton>
</h:form>
That can happen when
#{service}actually resolves tonull.When you use
@ManagedBeanwithout thenameattribute as you did, the managed bean name will by default resolve to the classname with 1st char lowercased (at least, conform the Javabeans spec), so yourMyServicebean will effectively get a managed bean name ofmyService.So there are basically 2 ways to fix this problem,
Use
#{myService}instead.Specify the managed bean name yourself so that it becomes available as
#{service}.Unrelated to the concrete problem, since you don’t seem to be interested in the ajax event, but rather in the action event, then you can also simplify the use of
<f:ajax>as follows:with
so that it’ll still work when the enduser doesn’t have JS enabled.
Finally, a business service is normally designed as a
@StatelessEJB, not as a JSF managed bean since it should have no direct relationship with a JSF view. You could then just use