简体   繁体   中英

Error: java.lang.NullPointerException in Client with WebService. How fixed it?

I'm doing a example about jax-ws-spring-integration. My project have following structure.

在此输入图像描述

In Client

在此输入图像描述

Here file UserClient.java

public class UserClient {
    static UserService service;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
//      System.out.println("From webservice"
//              + service.sayHello("Nguyen van a")); 
        service = new UserService();
        User user = service.getUser("hoaipham");
        System.out.println("Hello" + user.getUserName());
        System.out.println("Email" + user.getAge()); 
    }

}

Here file UserService.java

@WebService
@Component
public class UserService {
    @Autowired
    private UserBo userBo;
    @WebMethod(operationName = "getUser")
    public User getUser(String username){
        return userBo.loadUser(username);
    }
    @WebMethod(operationName = "say")
    public String sayHello(String name){
        return "Hanoi Java say hello to" + name;
    }
}

When i run "main" in Client then occur following error:

Exception in thread "main" java.lang.NullPointerException at edu.java.spring.ws.UserService.getUser(UserService.java:19) at Client.UserClient.main(UserClient.java:14)

Hm, it looks like Spring not working in the Client (in a different jvm).

Try to create a instance of AnnotationConfigApplicationContext and add your class to the Context (or let the instance scan the package).

EDIT:

Try

public class UserClient {
    static UserService service;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
//      System.out.println("From webservice"
//              + service.sayHello("Nguyen van a")); 
        service = new AnnotationConfigApplicationContext(UserService.class)
                          .getBean(UserService.class);
        User user = service.getUser("hoaipham");
        System.out.println("Hello" + user.getUserName());
        System.out.println("Email" + user.getAge()); 
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM