Reputation: 53916
I have a controller class :
@Controller
public class MyController {
@AutoWired
Service myservice
@RenderMapping
public display(){
//do work with myservice
}
}
I want to invoke the method display() from an external class but I am a null pointer exception.
Here is how I am invoking the display method from an external class :
new MyController.display()
But the instance myservice is being set to null.
How can I invoke MyController.display() and ensure the instance of myservice is not set to null ?
I think the problem is since I am creating a new instance of the controller the service is then not autowired ? But since the Spring controllers are singletons perhaps I can get access to the current instance of the controller ?
Update :
The reason I am trying this is I'm adding a config option to determine which controller display method should be implemented. Perhaps I should be using a super controller to determine which controller should be implemented ?
Upvotes: 0
Views: 354
Reputation: 10017
The idea is: use a abstract parent class!
// this class has no mapping
public abstract class MyAbstractController() {
@Autowired
MyService service
public String _display(Model model, ...) {
// here is the implementation of display with all necessary parameters
if(determine(..)){...}
else {...}
}
// this determines the behavior of sub class
public abstract boolean determin(...);
}
@Controller
@RequestMapping(...)
public class MyController1 extends MyAbstractController {
@RequestMapping("context/mapping1")
public String display(Model model, ...) {
// you just pass all necessary parameters to super class, it will process them and give you the view back.
return super._display(model, ...);
}
@Override
public boolean determine(...) {
// your logic for this
}
}
@Controller
@RequestMapping(...)
public class MyController2 extends MyAbstractController {
@RequestMapping("context/mapping2")
public String display(Model model, ...) {
// you just pass all necessary parameters to super class, it will process them and give you the view back.
return super._display(model, ...);
}
@Override
public boolean determine(...) {
// your logic for this
}
}
Hope this can help you...
Upvotes: 1
Reputation: 1381
I think the problem is since I am creating a new instance of the controller the service is then not autowired ?
Yes. You can get access to your beans using BeanFactory API in Spring. But invoking controllers directly sounds fishy. Can you tell us what are you trying to achieve and may be we can see if there is a standard way of doing it?
Upvotes: 0