Search code examples
javaspringspring-bootannotationsautowired

@Autowired is resulted as null


I am working with spring boot, In Controller, I tried to create an object using new operator, And tried to print object value its working.but for repository I used @Autowired but resulted in null

@RestController
public class SignupController {
    //@Autowired
    UserService userservice =new UserService() ;

    @GetMapping("/Allusers")
    public ResponseEntity<List<User>> allUsers() {
        System.out.print(userservice+"\n");
        List<User> userlist = userservice.getAllUsers();
        if (userlist.isEmpty()) {

            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(userlist, HttpStatus.OK);
    }

This is service class in which i Auto-wired "UserRepository userrepo;"

public class UserService {
     @Autowired
    UserRepository userrepo;

    public List<User> getAllUsers() {
        List<User> userlist = new ArrayList<User>();
        System.out.println(userrepo);
        userrepo.findAll().forEach(users -> userlist.add(users));
        System.out.println("hii");
        return userlist;
    }

Solution

  • Add the @Service annotation to UserService class and also a constructor to the same class. Like shown below;

    @Service
    public class UserService {
    
        private final UserRepository userrepo;
    
        public UserService(UserRepository userRepository) {
            this.userrepo = userRepository;
        }
    
        public List<User> getAllUsers() {
            List<User> userlist = new ArrayList<User>();
            System.out.println(userrepo);
            userrepo.findAll().forEach(users -> userlist.add(users));
            System.out.println("hii");
            return userlist;
        }
    }
    

    If you want to use @Autowired annotation, make sure that UserRepository class is annotated with @Service or @Controller or @Component. This is needed because, we need to say that the object is a Spring managed component.