2

i have the problem when calling web service using struts 2 and hibernate...

HTTP Status 500 - Unable to instantiate Action, actions.events.rest.EventController, defined for 'event' in namespace '/'Error creating bean with name 'actions.events.rest.EventController': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [actions.events.rest.EventController]: Constructor threw exception; nested exception is java.lang.NullPointerException

this is my source:

EventController :

public class EventController extends BaseAction implements ModelDriven<Object> {
private static final long serialVersionUID = 1L;
private String id;
private Object model; 

private static Map<String, Event> map;
{ 
    List<Event> events = services.getEvents();
    for(Event event : events){
        map.put(event.getId() + "", event);
    } 
}

public HttpHeaders index() {
    model = map;
    return new DefaultHttpHeaders("index").disableCaching();
}

public String add(){ 
    services.createEvent("Event1");
    return "SUCCESS";
}

public String getId() {
    return id;
}
public void setId(String id) {
    Integer iid = Integer.parseInt(id);
    model = services.getEventById(iid);
    this.id = id;
}

public Object getModel() {
    return model;
} 

BaseAction:

public class BaseAction extends ActionSupport {
// So that spring can inject the business singleton
protected Services services;

public void setServices(Services value) {
    services=value;
}

// For redirect results
protected String redirectUrl;

public String getRedirectUrl() {
    return redirectUrl;
}

public String redirect(String to) {
    redirectUrl = to;
    return "redirect";
}

When I debug, I got error in List<Event> events = services.getEvents(); in EventController. What can it be ?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Lumanyun
  • 63
  • 1
  • 8

1 Answers1

1
  • The exception is caused by the fact that
    you're referencing to the injected bean services from within a static initialization block:

    { 
        List<Event> events = services.getEvents();
        for(Event event : events){
            map.put(event.getId() + "", event);
        } 
    }
    

    remove it completely, do this kind of things in a prepare() method, or in a @PostConstruct method, or wherever but leave static blocks alone.

That said, you are following some bad practices:

  • you're returning "SUCCESS" while it should be "success" or SUCCESS (that is "success")

  • you're putting logic in setters, and it's better not

  • I'd also suggest to drop ModelDriven, drop Spring at all and use CDI, but this last is my humble opinion. BTW, ensure to take a look at what I'm talking about.

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243