In a Spring application, I have a class called Utility.java and the class is annotated with the @Service annotation. In that class I am trying to fetch a user in a function to be used globally in the project. Upon calling the user in a controller using the utility method created it throws nullpointer exception from the repository. Below is the code
//Utility.java file
@Service
public class Utility{
@Autowired static UserDao userDao;
public static User findActiveUser(String auth){
System.out.println("here is the username: " + auth);
User user = null;
try {
user = Utility.userDao.findBy...("user1", "ACTIVE"); //throws null here
}catch (Exception ex){
ex.printStackTrace();
}
return user;
}
//Controller annotated class
@Autowired Utility utility;
@GetMapping(value = "/success")
public String success(Authentication auth,HttpServletRequest request){
if (auth == null) {
return "index";
}
System.out.println("@dashboard success");
User user = utility.findActiveUser(auth.getName());
Everything look fine and good to go but still not working
You can't @Autowired
a static field.