How to #Autowire objects in Validator classes? - spring

Is it possible to Autowire an object in a Validation class? I keep getting null for the object that is supposed to be Autowired...

Are your Validation class an enabled Spring bean ??? If not, you always will get null for your object autowired. Make sure you have enabled your Validation class.
And do not forget enable The Annotation config bean post-processor (see <context:annotation-config /> element)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
</beans>
How to enable your Validation class as a managed Spring bean. Either
1° By using xml (As shown above)
<beans ...>
<bean class="AccessRequestValidator"/>
<context:annotation-config />
</beans>
2° By using annotation instead (Notice #Component just above class)
#Component
public class AccessRequestValidator implements Validator {
}
But to enable Spring annotated component scanning, you must enable a bean-post processor (notice <context:component-scan element)
<beans ...>
<context:annotation-config />
<context:component-scan base-package="<PUT_RIGHT_HERE_WHICH_ROOT_PACKAGE_SHOULD_SPRING_LOOK_FOR_ANY_ANNOTATED_BEAN>"/>
</beans>
Inside your Controller, just do it (Do not use new operator)
Choose one of the following strategies
public class MyController implements Controller {
/**
* You can use FIELD #Autowired
*/
#Autowired
private AccessRequestValidator accessRequestValidator;
/**
* You can use PROPERTY #Autowired
*/
private AccessRequestValidator accessRequestValidator;
private #Autowired void setAccessRequestValidator(AccessRequestValidator accessRequestValidator) {
this.accessRequestValidator = accessRequestValidator;
}
/**
* You can use CONSTRUCTOR #Autowired
*/
private AccessRequestValidator accessRequestValidator;
#Autowired
public MyController(AccessRequestValidator accessRequestValidator) {
this.accessRequestValidator = accessRequestValidator;
}
}
UPDATE
Your web app structure should looks like
<CONTEXT-NAME>/
WEB-INF/
web.xml
<SPRING-SERVLET-NAME>-servlet.xml
business-context.xml
classes/
/com
/wuntee
/taac
/validator
AccessRequestValidator.class
lib/
/**
* libraries needed by your project goes here
*/
Your web.xml should looks like (NOTICE contextConfigLocation context-param and ContextLoaderListener)
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<!--If your business-context.xml lives in the root of classpath-->
<!--replace by classpath:business-context.xml-->
<param-value>
/WEB-INF/business-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name><SPRING-SERVLET-NAME></servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name><SPRING-SERVLET-NAME></servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
Your <SPRING-SERVLET-NAME>-servlet.xml should looks like (Notice i am using Spring 2.5 - replace if you are using 3.0)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!--ANY HANDLER MAPPING-->
<!--ANY VIEW RESOLVER-->
<context:component-scan base-package="com.wuntee.taac"/>
<context:annotation-config/>
</beans>

Trying to follow what you show above, I am still getting a null pointer:
context.xml:
<context:annotation-config />
<context:component-scan base-package="com.wuntee.taac"/>
AccessRequestValidator.java
package com.wuntee.taac.validator;
#Component
public class AccessRequestValidator implements Validator {
#Autowired
private UserAccessCache userAccessCache;
...
}
business-context.xml:
<bean id="userAccessCache" class="com.wuntee.taac.controller.UserAccessCache">
<property name="cadaDao" ref="cadaDao" />
<property name="adDao" ref="adDao" />
</bean>
Does the scanner recursively scan the tree?

Related

No mapping found for HTTP request with URI [/FitnessTracker/]

I am getting an warnning in springmvc
as No mapping found for HTTP request with URI [/FitnessTracker/] in DispatcherServlet with name 'fitTrackerServlet'
INFO: FrameworkServlet 'fitTrackerServlet': initialization completed in 2194 ms
Feb 26, 2017 9:43:08 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/FitnessTracker/] in DispatcherServlet with name 'fitTrackerServlet'
When i press url http://localhost:8080/fitnessTracker/ I am getting 404 error.
Thanks
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>fitTrackerServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<display-name>Archetype Created Web Application</display-name>
</web-app>
and my servlet-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.pluralsight.controller"></context:component-scan>
<!--
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>
and my controller
#Controller
public class HelloController {
#RequestMapping(value = "/greeting")
public String sayHello (Model model) {
System.out.println("Test");
model.addAttribute("greeting", "Hello WorldX");
return "hello";
}
}
Does your component-scan base-package match the package where your HelloController is in? If not, that is the problem.
<context:component-scan base-package="com.pluralsight.controller"></context:component-scan>
Configures component scanning directives for use with #Configuration
classes. Either basePackageClasses() or
basePackages() (or its alias value()) may be specified to define
specific packages to scan.
Spring does not find your HelloController and so doesn't map anything.
Otherwise you could also follow these steps.
I am wondering why you have you application configured with XML. With this tool you can start a maven project with a Spring boot application that will be, by default, already configured to build exactly what you want.
Then you only need a class with:
#RestController
#RequestMapping("/fitnessTracker")
public class HelloController {
#RequestMapping(value = "/greeting")
public String sayHello (Model model) {
System.out.println("Test");
model.addAttribute("greeting", "Hello WorldX");
return "hello";
}
}
And that's it, Spring will do the rest for you ;)
In my case the problem was that i was using this url-pattern
<url-pattern>/*</url-pattern>
instead of this
<url-pattern>/</url-pattern>
and also i had to add
#RequestMapping(value = "/fitnessTracker")
under the
#Controller
annotation.
I found the solution at : https://www.baeldung.com/spring-mvc-404-error for the pattern.

#PostConstuct does not appear to work and #autowire gives an error

I am new to spring and am creating a spring web application.
The application I'm writing has a Class PreLoadService. In this class is a method defined with #PostConstruct that calls a DAO to load the data. The DAO instance is declared in the class with the #autowired.
The Controller for the JSP then declares an instance of the PreLoadService and calls the getter to retrieve the data that should have been loaded in the #PostConstruct. The data is never loaded and an exception is also thrown on the #autowired.
Since this did not work I tried a simple Hello World version to write a message and received the same issue. I will post this. In the WEB_INF folder I have a web.xml and a spring3-servlet.xml. In the SRC folder I have an applicationContext.xml. I am running on Tomcat 7.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>root.webpath</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring3</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring3</servlet-name>
<url-pattern>*.html</url-pattern>
<url-pattern>/</url-pattern>
</servlet-mapping></web-app>
spring3-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--will allow Spring to load all the components from package and all its child packages-->
<mvc:annotation-driven />
<context:component-scan
base-package="com.nikki.spring3.controller" />
<!-- will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView. -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.nikki.spring3">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean id="helloWorldService"
class="com.nikki.spring3.beansit.HelloWorldService">
<property name="message" value="Preloading Init Config and Data" />
HelloWorldService
public class HelloWorldService {
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
System.out.println("Your Message : " + message);
return message;
}
#PostConstruct
public void init(){
System.out.println("Bean is going through init.");
}
#PreDestroy
public void destroy(){
System.out.println("Bean will destroy now.");
}
}
HelloWorldController
#Controller
public class HelloWorldController {
#Autowired
HelloWorldService helloWorldService;
/* RequestMapping annotation tells Spring that this Controller should
* process all requests beginning with /hello in the URL path.
* That includes /hello/* and /hello.html.
*/
#RequestMapping("/hello")
public ModelAndView helloWorld() {
String message =helloWorldService.getMessage();
//"Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
Error Message
Exception
SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0':
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'helloWorldController':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: com.nikki.spring3.beansit.HelloWorldService com.nikki.spring3.controller.HelloWorldController.helloWorldService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.nikki.spring3.beansit.HelloWorldService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
I appreciate any help. Thanks.
If you have config files other than xxx-servlet.xml you need to let know spring that these files exists. To do that you have to use contextConfigLocation along with ContextLoadListener. Try to add the following lines in your web.xml. If the applicationContext.xml exists in WEB-INF folder of the project use the following.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
I think you had your applicationContext.xml under src folder. In that case use as below
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
Try creating an interface for HelloWorldService and autowire with that interface in your controller. Spring create bean of proxy of class HelloWorldService, so HelloWorldService itself may not be available to be autowired. Try it.
in your case you want to inject a bean that has not yet created
add #Service
#Service
public class HelloWorldService { ...... }

Trouble spring injection in JSF2 Bean with annotation

I have a trouble with Spring Injection in my web project. I must use in a JSF2 bean.
Show my work :
SgbdServiceImpl.java (shorted)
#Service
public class SgbdServiceImpl implements SgbdService {
#Override
public List<Sgbd> findAll() {
return null;
}
#Override
public Sgbd findOneByName(String nom) {
return null;
}
}
SgbdBean
#Component
#SessionScoped
#ManagedBean(name="sgbd")
public class SgbdBean {
#Autowired
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
I put this configuration in the file : web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
This Spring configuration in applicationContext.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="main.java.com.erdf.agir.services" />
</beans>
And, in faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
I would like call findAll() from service but i obtain all time nullPointerException from sgbdService attribut (Autowired failled ?)
I follow this example : http://rsuna.blogspot.fr/2013/05/how-to-integrate-jsf-20-with-spring-3.html
Did I miss anything ?
You have a context clash; using both #Component and #ManagedBean on the same class definition put your bean in two contexts: JSF and Spring's. Let's now establish that #Autowired will not work in the JSF context.
You could get rid of the spring-based annotations and go with a JSF-centric setup. What this will leave with you with
#SessionScoped
#ManagedBean(name="sgbd")
public class SgbdBean {
#ManagedProperty(value="#{sgbdServiceImpl}")
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
You could stick with a strictly spring-centric approach with
#Component
public class SgbdBean {
#Autowired
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
Things I have encountered
1) Better to mention service name with annotation - #Service("sgbdService")
2) Rather than #ManagedBean it is better to use #Qualifier annotation -
#Qualifier("sgbdBean")
3) Add <context:sping-configured/> entry to applicationContext.xml file
4) Try with top level component scan entry as
<context:component-scan base-package="main.java.com.erdf" />

#Autowired is not working with jersey and spring

When I am running test at that time #Autowired is working but when I run the web app and try to fetch data at that time its throwing null pointer exception.
this is my controller
In this BuyerRepo is always null
import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import com.retail.repository.BuyerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/buyer")
#Component
public class BuyerController {
#Autowired
private BuyerRepo buyerRepo;
#GET
#Produces("application/json")
public Buyer searchFields() throws InvalidIdException {
String buyerId = "51";
Buyer buyer;
try {
buyer = buyerRepo.getBuyer(Long.parseLong(buyerId));
} catch (NumberFormatException e) {
buyer = buyerRepo.getBuyer(buyerId);
}
return buyer;
}
}
In repository entity manager is always null
this is buyerRepository
import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import org.springframework.stereotype.Repository;
import javax.persistence.NoResultException;
#Repository
public class BuyerRepo extends AbstractRepository {
public Buyer getBuyer(String buyerName) throws InvalidIdException {
javax.persistence.Query buyerId = entityManager.createNativeQuery("select b.buyer_id from buyer b where b.name = :name").setParameter("name", buyerName);
Integer id;
try {
id = (Integer) buyerId.getSingleResult();
} catch (NoResultException e) {
return null;
}
return getBuyer(id);
}
public Buyer getBuyer(long buyerId) throws InvalidIdException {
Buyer buyer = entityManager.find(Buyer.class, buyerId);
if (buyer == null) throw new InvalidIdException("Invalid Article ID");
return buyer;
}
}
this is applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.retail"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost/retail"/>
<property name="username" value="retail_user"/>
<property name="password" value="password"/>
</bean>
<bean id="entityManagerOne" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.retail"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerOne"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
this is servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.retail" />
</beans>
this is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
<servlet>
<servlet-name>retail</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.retail.web</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>retail</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
/WEB-INF/servlet-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
You have to wire a interface instead of class. so there are two ways:
To let BuyerRepo to implement one interface
Useing #Inject or #Resource instead of #Autowired
I Have encountered this situation,
you need to add some jar file
gradle project:
compile group: 'org.glassfish.jersey.ext', name: 'jersey-spring3', version: '2.22.2'
maven project:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>2.22.2</version>
</dependency>
another solution is web.xml file:
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>cn.ice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
You can try using the SpringServlet instead of the jersey provided servlet container to achieve Jersey-Spring integration.
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
The documentation for this class states :
A servlet or filter for deploying root resource classes with Spring integration.
This class extends ServletContainer and initiates the WebApplication with a Spring-based
IoCComponentProviderFactory, SpringComponentProviderFactory, such that instances of resource and provider
classes declared and managed by Spring can be obtained.
Classes of Spring beans declared using XML-based configuration or auto-wire-based confguration will be
automatically registered if such classes are root resource classes or provider classes. It is not necessary to provide
initialization parameters for declaring classes in the web.xml unless a mixture of Spring-managed and Jersey-
managed classes is required.
The servlet supports configuration of child applicationContexts, see CONTEXT_CONFIG_LOCATION.
Looks like your buyerRepo has no public setter. It's also not possible to set it through the constructor. How about write a setter for it and put the #Autowired annotation on the setter instead. Like this:
#Repository
public class BuyerRepo extends AbstractRepository {
private BuyerRepo buyerRepo;
#Autowired
public void setBuyerRepo(BuyerRepo buyerRepo)
{
this.buyerRepo = buyerRepo;
}
//...Other code is omitted.
}

Spring configuration in JBossWS

I'm trying to expose a web service using JBossWS (native stack) and also take advantage of Spring's dependency injection. Here is a scrubbed down version of my code:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test Service</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>EndpointService</servlet-name>
<servlet-class>com.blah.webservice.EndpointService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EndpointService</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:spring-configured />
<context:load-time-weaver />
<context:annotation-config />
<context:component-scan base-package="com.blah.webservice" />
</beans>
EndpointService.java
package com.blah.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
#WebService
#SOAPBinding(parameterStyle=SOAPBinding.ParameterStyle.BARE)
public class EndpointService {
private TestService testService;
public EndpointService() {}
#Autowired
public EndpointService(TestService testService) {
this.testService = testService;
}
#WebMethod
public String endpointEcho(String echo) {
return echo;
}
#WebMethod
public String serviceEcho(String echo) {
return testService.serviceEcho(echo);
}
}
TestService.java:
package com.blah.webservice;
import org.springframework.stereotype.Service;
#Service
public class TestService {
public TestService() {}
public String serviceEcho(String echo) {
return echo;
}
}
When I build this and deploy to JBoss, it starts up just fine and I can see Spring is pre-instantiating my classes but when I issue calls to the web service, endpointEcho works as expected while serviceEcho throws a NullPointerException. It seems that when JBossWS instantiates the endpoint class, it isn't finding out about my Spring configuration. Is there a simple way that I can tell JBossWS about Spring? I feel like I'm either missing some very small detail, or I'm approaching this all wrong. Any ideas?
Your service must extend SpringBeanAutowiringSupport to be able to take advantage of the autowiring support.

Resources