How to autowired spring service into a jsp?

You should not even try to do that... JSP are translated to java source and compiled to java classes by the servlet container, and the Java EE specification does not say where they go, so you cannot have spring scan them, so annotation is not an option

Worse, the JSP cannot be Spring beans because they are created by the servlet container outside of the application context, so XML injection cannot work either.

And even full AspectJ cannot be used because once again you have no control on where JSP classes lie so you cannot even use a load-time weaver on them.

The problem is not that "that's not recommended to do it ", it is that JSP are special classes managed by the servlet container. You can use Java code in scriplets, but you cannot manage them as normal Java classes.

BTW, and more generaly, don't you think that there can be good reasons for not recommending too much Java code in scriptlets?


I think you may not use @Autowired annotation in the JSP. But you have used some Support class. I can help you with these solutions:
Solution 1:
if You are using Spring MVC,
just simply pass your service to the JSP using ModelAndView.
Example:

Suppose You have Controller:

@Controller
public void TestController{

    @Autowired
    private TestService tService;

    @RequestMapping("someURL")
    public ModelAndView displayPage{
    //do some stuff
    return new ModelAndView("myView").addObject("tService",tService);
    }
}

JSP:

<html>
...
${tService.myMethodIWantToUse(..)}
...
</html>



Solution 2:
Use ApplicationContext in your JSP to access any bean like this

Example:

@Component("tsc")
public void TestServiceClass{
//Your code goes here
}

Inside JSP:

ApplicationContext aC = RequestContextUtils.getWebApplicationContext(request);
TestServiceClass tsc1 = (TestServiceClass) aC.getBean("tsc");
//Code to access your service Classes methods.

Hope this will help.