Autowiring in servlet
Solution 1
I followed the solution in the following link, and it works fine: Access Spring beans from a servlet in JBoss
public class MyServlet extends HttpServlet {
@Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
Solution 2
Remove the @Configurable
annotation from your servlet and add:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
at the first line of your init() method.
Mahmoud Saleh
I am Mahmoud Saleh an Enthusiastic Software Engineer, Computer Science Graduate, Experienced in developing J2EE applications, Currently developing with Spring,JSF,Primefaces,Hibernate,Filenet. Email: [email protected] Linkedin: https://www.linkedin.com/in/mahmoud-saleh-60465545? Upwork: http://www.upwork.com/o/profiles/users/_~012a6a88e04dd2c1ed/
Updated on March 01, 2020Comments
-
Mahmoud Saleh over 4 years
i want to use spring autowiring in servlet so here's my code:
@Configurable public class ImageServlet extends HttpServlet { @Autowired private SystemPropertyDao systemPropertyDao; @Override public void init() throws ServletException { String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER); }
while the
SystemPropertyDao
is annotated with@Repository
and my applicationContext.xml:
<context:component-scan base-package="com.basepackage" /> <mvc:annotation-driven /> <context:annotation-config /> <context:spring-configured/>
web.xml:
<servlet> <servlet-name>imageServlet</servlet-name> <servlet-class>com.xeno.basepackage.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>imageServlet</servlet-name> <url-pattern>/myimages/*</url-pattern> </servlet-mapping>
sometimes the autowiring works and sometimes it doesn't (the reference to the spring bean systemPropertyDao is null), can anyone please tell me if i am missing something?
-
hiway over 10 yearsthanks very much. At first I use
Resource
annotation, it doesn't work, andAutowired
works well. -
Suryaprakash Pisay almost 10 yearsThank you very much, but why they specifically mentioned in jBoss?? Won't it work in weblogic??
-
Chucky about 9 yearsIt will work in Weblogic and even in Tomcat ! This is only the title of the documentation: the solution is actually relying upon the standard servlet api and pure Spring classes.