开发者

JSF 2.0 @ManagedProperty is not been set

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 v开发者_如何转开发alue="Call Service">
            <f:ajax listener="#{myController.callToService}"/>
        </h:commandButton>
</h:form>


That can happen when #{service} actually resolves to null.

When you use @ManagedBean without the name attribute 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 your MyService bean will effectively get a managed bean name of myService.

So there are basically 2 ways to fix this problem,

  1. Use #{myService} instead.

    @ManagedProperty("#{myService}")
    private MyService service;
    
  2. Specify the managed bean name yourself so that it becomes available as #{service}.

    @ManagedBean(name="service")
    @ApplicationScoped
    public class MyService {
    
    }
    

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:

<h:commandButton value="Call Service" action="#{myController.callToService}">
    <f:ajax />
</h:commandButton>

with

public void callToService() {
    System.out.println(service);
}

so that it'll still work when the enduser doesn't have JS enabled.

Finally, a business service is normally designed as a @Stateless EJB, not as a JSF managed bean since it should have no direct relationship with a JSF view. You could then just use

@EJB
private MyService service;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜