Search code examples
springspring-mvcautowiredrequest-mappingclass-level

calling a method by class level annotated with @RequestMapping that includes an autowired class


I am trying to call a method that is annotated with @RequestMapping(signIn) through a class level (from method: authentication) like so:

@RequestMapping(value = /authenticate, method = RequestMethod.POST)
public @ResponseBody Response authentication(HttpServletRequest request) 
{
    UserController user = new UserController();     
    return user.signIn(request, null);
}

and my controller looks like:

@Autowired
private UserManager userManager;

@RequestMapping(value = /signin, method = RequestMethod.POST)   
public @ResponseBody Response signIn(HttpServletRequest request) {      
        JsonObject json = Misc.parseJson(request);
        String lang = Misc.getLang(request);
        user.setEmail(Misc.getEmail(json));
        user.setPassword(Misc.getEncryptedPassword(json));

        return ResponseUtils.success(userManager.auth(user, lang));

}

user manager is annotated with @component:

   @Component
   public class UserManager {
        public User auth(User user, String lang) {
         ....
        return user;
       }
   }

Problem is when I call the method "signIn" and just new-up a UserController instance through "/authenticate" mapping, the UserManager becomes NULL. So now I'm assuming that autowiring doesn't work when it's done this way.

Is there any other way to call the signIn method? I would hate to copy paste an already existing code to another class just to get this to work...


Solution

  • So in the end I just separated the logic instead. Though one solution that I tried and I could have used was to just add another mapping to the signIn method instead of adding a new method in the other class since the logic was similar. Still I opted for a separate logic instead since there were a lot of unnecessary code in the signIn method for my purpose.