I need to inject a object
of a java class in spring controller
through applicaionContext.xml
. My controller will be ,
@Controller
public class SpringController{
private MyClass obj;
}
I know I can do it with @Autowired
annotation.
Is this really good to create a object for a controller
through applicaionContext.xml
? Also can I inject a object of a class in controller using the <property>
tag inside a <bean>
tag ?
Is this really possible ? or please forgive me if it is a stupid question.
I need to know the possible ways for how to inject a object of a class in Spring controller ?
If you want to inject an object in a controller and you particularly want to you use xml,then instead of component scanning of Controller you should create a bean of the controller class of singleton scope in the application context. Your controller class need not be annotated with @Controller.
you then have to you extend some Controller also like AbstractCommandController, AbstractController, AbstractFormController, AbstractWizardFormController, BaseCommandController, CancellableFormController, MultiActionController SimpleFormController, UrlFilenameViewController
Now to inject a particular object you can use Either Constructor and Setter based injection. or you can use Autowring by name or type to auto inject the object. Make sure that you have also declared the bean of that object also in Application Context.
After a DispatcherServlet has received a request and has done its work to resolve locales, themes and suchlike, it then tries to resolve a Controller, using a HandlerMapping. When a Controller has been found to handle the request, the handleRequest method of the located Controller will be invoked; the located Controller is then responsible for handling the actual request and - if applicable - returning an appropriate ModelAndView.
Thats it.