I am building a web application using spring and hibernate. I wanted to build the server side table for that I need a method that is written in Service class. But to execute it successfully I need to autowire it to the repected class as for now it is giving a Null Pointer Exception accessing the table.
@Autowired annotation can be applied on variables and methods for autowiring byType. We can also use @Autowired annotation on constructor for constructor based spring autowiring. For @Autowired annotation to work, we also need to enable annotation based configuration in spring bean configuration file.
The answer for your question is YES. You can use autowired in thread class.
@Autowired can be used only on "a constructor, field, setter method or config method".
The beans can be wired via constructor or properties or setter method. For example, there are two POJO classes Customer and Person. The Customer class has a dependency on the Person. @Autowired annotation is optional for constructor based injection.
No you can't use @autowired
in JSP. If you need a bean in JSP, you can use the following :
ApplicationContext ac = RequestContextUtils.getWebApplicationContext(request);
ac.getBean("yourBeanName");
Edited to :-
Example Bean :
@Component("abcBean")
public Abc{
public void sysout(){
System.out.printn("Hello world");
}
}
In JSP:
You can use this spring managed singleton bean as:
ApplicationContext ac = RequestContextUtils.getWebApplicationContext(request);
Abc abc = (Abc) ac.getBean("abcBean");
abc.sysout();
Please post if anything else is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With