1

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

2 Answers 2

1

You can't @Autowired a static field.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to remove static word from this line @Autowired static UserDao userDao; or implement additional logic to autowire value to the static field.

1 Comment

Example of static autowiring you can find here: stackoverflow.com/questions/1018797/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.