Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use @autowired in jsp. If yes then how.?

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.

like image 689
HVT7 Avatar asked Dec 11 '13 11:12

HVT7


People also ask

Where @autowired can be used?

@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.

Can we use Autowire in any class?

The answer for your question is YES. You can use autowired in thread class.

Can we use @autowired at method level?

@Autowired can be used only on "a constructor, field, setter method or config method".

Can we use @autowired in pojo?

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.


1 Answers

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.

like image 195
Amit Sharma Avatar answered Oct 13 '22 02:10

Amit Sharma