spring #autowired NullPointerException from one Controller to another - spring

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?

Related

Spring application context bean creation issue with latest spring version

I have a project which uses an old spring.jar (1.2.6),from this project, I am expected to call a newer version (spring version 5.0.7) spring boot project's method. Below is the way I am creating my bean in old version project.
I am getting NullPointer exception while creating the Autowired bean.
Create bean from XML:spring
test-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "qvc-spring-beans.dtd">
<beans>
<bean name="testPci" class="com.test.client.TestPci">
</bean>
</beans>
sampleParent-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans SYSTEM "spring-beans.dtd">
<beans>
<import resource="classpath:/com/test/test-context.xml" />
<bean id="classA" class="com.test.A" >
<property name="testPci">
<ref bean="testPci"/>
</property>
</bean>
</beans>
Java code old spring project:
package com.test;
public class A{
private TestPci testPci;
private ApplicationContext ctx;
public TestPci getTestService() {
if (!StringUtils.isValid(ctx)) {
ctx = new ClassPathXmlApplicationContext("./com/test/test-context.xml");
}
if (!StringUtils.isValid(this.testPci)) {
if (StringUtils.isValid(ctx)) {
testPci = (TestPci) ctx.getBean("testPci");
TestPci testPci = (TestPci) ctx
.getBean("testPci");
this.setSecureTestService(testPci);
}
}
return this.getSecureTestService();
}
public TestPci getSecureTestService() {
return testPci;
}
public void setSecureTestService(TestPci testPci) {
this.testPci = testPci;
}
public void methodA(){
//Calling newer code form old spring code:
testPci.testing("1", "2", "3");
}
}
Calling "TestPci" class as above, but when trying to call using the above, it actually calls the "TestPci"."testing" method. But the object autowired as "testWebClientService" is returning as null. I would like to get the object created instead it returns null.
New spring version class:
#Service
#EnableConfigurationProperties(TestWebClientProperties.class)
#Configurable
public class TestPci{
#Autowired
private TestWebClientService testWebClientService;
public Map<String, String> testing(String a, String b, String c) throws Exception {
Map<String, String> map = testWebClientService.find(a, b, c);
System.out.println("**=="+map.get(0));
return map;
}
}
Adding junit which is used to call the TestPci class from newer version of spring:
#RunWith(SpringJUnit4ClassRunner.class)
#EnableConfigurationProperties(TestWebClientProperties.class)
#SpringBootTest(classes = { TestWebClientService.class, TestPci.class }, webEnvironment = WebEnvironment.NONE)
public class TestJunit {
#MockBean(name="restTemplate")
public RestTemplate restTemplate;
#Autowired
private TestPci testPci;
#Test
public void ff() throws Exception {
testPci.testing("1","1","1");
}
}

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

Autowiring in servlet

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.

Invoke EJB from spring using rest jersey

First, the problem is when I invoke the ejb from the rest servlet, the ejb is always null.
I have a rest web service developed in jersey + spring 3.0.5. And an EJB 3.1 for services.
I have package the war and jar in an ear so my application looks like (I'm using maven for dependency):
+ear
++war
++jar
I was wondering how I could call the services in the jar file from my classes in the war file. As far as I remember it's through JNDI and I need to expose the ejb apis? How should I do that?
I'm sure the EJB are created successfully because I can see the log in the server like this:
Portable JNDI names for EJB UserServiceBean :
[java:global/demo-cg-ear-0.0.1-SNAPSHOT/demo-cg-ejbs/UserServiceBean!com.demo.cg.service.user.UserServiceBeanLocal,
java:global/demo-cg-ear-0.0.1-SNAPSHOT/demo-cg-ejbs/UserServiceBean]|#]
But the problem is when I invoke it in the rest jersey servlet, it's always null:
#Path("/payment")
#Stateless
public class PaymentService {
#Path("/payment")
#Stateless
public class PaymentService {
#EJB
private UserServiceBeanLocal userServiceBean;
#GET
#Path("/hello")
public Response savePayment() {
String result = userServiceBean.getName();
return Response.status(200).entity(result).build();
/* return Response.status(200).entity("hello edward").build(); */
}
}
My applicationContext.xml file
<context:annotation-config />
<context:component-scan base-package="com.sido" />
<context:property-placeholder location="WEB-INF/build.properties" />
<!-- <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
<property name="alwaysUseJndiLookup" value="true" /> </bean> -->
<jee:jndi-lookup id="userServiceBean"
jndi-name="java:global/sido-cg-ear-0.0.1-SNAPSHOT/sido-cg-ejbs/UserServiceBean"
resource-ref="true" lookup-on-startup="true"
expected-type="com.sido.cg.service.user.UserServiceBeanLocal"
proxy-interface="com.sido.cg.service.user.UserServiceBeanLocal"></jee:jndi-lookup>
UserBean class
#Interceptors(SpringBeanAutowiringInterceptor.class)
#Stateless
public class UserServiceBean implements UserServiceBeanLocal {
private String name;
public UserServiceBean() {
name = "edward";
}
#PostConstruct
private void init() {
name = "edward";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Thanks,
czetsuya
For those who are interested this is how I did it: http://czetsuya-tech.blogspot.com/2012/05/how-to-call-stateless-ejb-from-spring.html

Resources