Autowiring in servlet - spring

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?

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());
}
}

Remove the #Configurable annotation from your servlet and add:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
at the first line of your init() method.

Related

propleme with the injection of dependence of spring

For the project that we create during my formation we use spring to make dependency injection.
we have a servlet-context.xml file with the following configuration:
<context:component-scan base-package="fr.autoquiz3000" />
I created several controllers and I have no problem injecting the dao for example:
package fr.autoquiz3000;
#Controller
#RequestMapping("/public")
public class PublicController {
#Autowired
private UserDao uDao;
#GetMapping("/connection")
public ModelAndView getConnection() {
return new ModelAndView("public/viewConnexion");
}
but I try to create a filter with a dao like this:
package fr.autoquiz3000;
#Component
public class CountQuizStudent implements Filter {
#Autowired
private QuizToDoDao qtdDao;
and I have this error:
qtdDao= null
java.lang.NullPointerException
at fr.autoquiz3000.CountQuizStudent.doFilter(CountQuizStudent.java:41)
Someone could explain to me what I'm doing wrong!
thank you!
For filters override init method and set Spring beans there:
#Override
public void init(FilterConfig filterConfig) throws ServletException {
WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
userDao = springContext.getBean(UserDao.class);
}
or use DelegatingFilterProxy:
<filter>
<filter-name>yourFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>yourFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
#Component("yourFilter")
public class YourFilter implements Filter {
// auto wiring available as it's just Spring Bean
}

spring #autowired NullPointerException from one Controller to another

I work with Spring and I want to call from one Controller to another Controller.
This is my application-context file
<context:annotation-config />
<context:component-scan base-package="com.renfe.cme.mybatis,renfe.informes.resumenjornadas" />
<bean id="resumenMensualJornadasBO" class="renfe.informes.resumenjornadas.ResumenMensualJornadasBO">
</bean>
I call the first Controller from a servlet
ResumenMensualJornadasServlet resumenMensualJornadasServlet = new ResumenMensualJornadasServlet();
resumenMensualJornadasServlet.llamarController(req);
This is ResumenMensualJornadasServlet
#Controller
public class ResumenMensualJornadasServlet
{
#Autowired
private ResumenMensualJornadasBO resumenMensualJornadasBO;
public void llamarController(HttpServletRequest req) throws Exception{
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
}
}
ResumenMensualJornadasBO.java is
#Component
public class ResumenMensualJornadasBO
{
#Autowired
private ResumenMensualJornadasManager resumenMensualJornadasManager;
public void cargarParametrosInforme(HttpServletRequest req) throws Exception
{
String matricula = StringUtils.recuperarParametro(req, "matricula");
String fechaDesde = StringUtils.recuperarParametro(req, "fechadesde");
String fechaHasta = StringUtils.recuperarParametro(req, "fechahasta");
resumenMensualJornadasManager.obtenerDatos(matricula, fechaDesde, fechaHasta);
}
}
I get NullPointerException when I call
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
How can I fix the error in #Autowired?
EDITED
In the web.xml I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/renfe/cme/recursos/spring/applicationContext-*.xml</param-value>
<description>Spring files location</description>
</context-param>
How can I get the bean from this context?

Autowired object is null in Rest controller when deployed on JBoss EAP

I am using Springboot and RESTEasy to create a small webapp, in my Controller class I am doing #Autowire for my Dao class. Whenever I deploy the code, the dao reference variable always ends up with null value. I have used #Component for controller and in mail Application class I have used #SpringBootApplication and at my dao class also I have added #Repository and #Service.
Please give some suggestions where exactly i am doing wrong?
Note: Works fine if I run it as a standalone Springboot app. But this issue occurs when deploy in JBoss server.
Code format is displayed below: While debugging, at line , List<DataDto> dataList = dao.findData(); always dao is null, because of which API call fails.
#Component
#Path("/")
public class apiController {
#Autowired
private ApiDao dao;
public void setApiDao(ApiDao dao) {
this.dao = dao;
}
#GET
#Path("/getData")
#Produces(MediaType.APPLICATION_JSON)
public List<DataDto> getDetails(){
List<DataDto> dataList = dao.findData();
return logList;
}
}
Dao class code is as below:
#Repository
#Service
public class ApiDao {
private final Logger log = LoggerFactory.getLogger(ApiDao.class);
private JdbcTemplate jdbcTemplate;
#Autowired
public ApiDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<SystemEntity> findData() throws SystemException{
return entityList;
}
}
And for configuration i have used below code and in pom.xml added required dependencies:
#Component
#ApplicationPath("/rest/")
public class JaxrsApplication extends Application {
}
The Problem
JBoss provides inbuilt support for RESTEasy. So in this case the apiController is initialized twice:
Once by Spring
Once by JBoss.
The autowiring happens under the hood in the instance initialized by spring but when a call is triggered to the apiController it is handled by the instance initialized by JBoss.
Solution
Disable JBoss from initializing RESTEasy Controllers. In your spring boot application create a web.xml under src/main/webapp/WEB-INF and add the following context parameters:
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>

Spring interceptor not invoked

I am using spring and resteasy integration for exposing some REST based services. I am planning to use interceptors for logging and authentication but facing issues with interceptor invocation.
Controller class (using #Path for rest services)
#Controller
#Path("/v1.0/create")
public class ContollerClass{
#POST
#Path("/artifact")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String someMethod(SampleVO sampleVO,#Context HttpServletRequest request) {
// Some functionality
}
acctrest-servlet.xml :
<context:component-scan base-package="com.comp.abc.xyz" />
<import resource="classpath:springmvc-resteasy.xml" />
<mvc:interceptors>
<bean class="com.comp.abc.xyz.interceptor.AuthenticationInterceptor" />
</mvc:interceptors>
Interceptor :
public class AuthenticationInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("pre handle ************************");
log.info("before handler execution");
String requestID = Long.toString(System.currentTimeMillis());
log.debug("request ID is {} :: ", requestID);
return true;
}
Web.xml
<servlet>
<servlet-name>acctrest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>acctrest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Except the interceptor invocation, rest of the flow is working fine.

Dispatcher Servlet in Spring Boot

In my Spring Boot application with packaging type as war, i am configuring Spring MVC. As i understand we dont have to configure Dispatcher Servlet Manually. However, i old style of web.xml i used to configure Dispatcher Servlet and then i used to pass contextClass and contextConfigLocation as follows
<servlet>
<description>
</description>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>contextClass</description>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<description>contextConfigLocation</description>
<param-name>contextConfigLocation</param-name>
<param-value>com.xxx.yyy.jdorderspringmvcweb.config.SpringMvcConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I belive this was to indicate that SpringMvcConfig (my custom class with spring mvc configuration) is the configuration class for Spring MVC..
However, In spring boot if Dispatcher Servlet is configured Automatically, how can i pass my custom class to dispatcher Servlet ?
In my Spring Boot application, my SpringMvcConfig class extends from WebMvcConfigurerAdapter and is annotated with #Configuration class
Help Needed...
Right in the configuration class which is annotated by #Configuration you could define your dispatcherServlet and pass init-parameter to it.
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet());
registrationBean.addInitParameter("contextClass","org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
registrationBean.addInitParameter("contextConfigLocation","com.xxx.yyy.jdorderspringmvcweb.config.SpringMvcConfig");
return registrationBean;
}
Another way would be to create a paramter map and then set parameter for registration bean. This stream shows how to do it.
I think you have to create a config class as follow:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

Resources