Reputation: 79
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...
Upvotes: 0
Views: 1246
Reputation: 79
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.
Upvotes: 0
Reputation: 3778
I don't know why you not moving logic into separate Service classs, but try this:
UserController.java
public UserController(UserManager userManager) {
this.userManager = userManager;
}
and then inside controller where authentication resource method is located:
@Autowired UserManager userManager;
@RequestMapping(value = /authenticate, method = RequestMethod.POST)
public @ResponseBody Response authentication(HttpServletRequest request) {
UserController user = new UserController(userManager);
return user.signIn(request);
}
Upvotes: 0
Reputation: 49
It's not problem with @Autowired .There are two type of Annotation firstly method base annotation and field level annotation. You just used field level annotation.Check your import class with "org.springframework.beans.factory.annotation.Autowired" or it can be problem with initiation of "UserManager"
Upvotes: 0
Reputation: 69450
Autowiering only works in spring managed bean. If you create a class with new
keyword, it is not a spring managed bean and autowiering would not work.
You can try to autowire the class which contains the method which is annotated or better put the code in a service class which can be used by both methods.
Upvotes: 1