Spring: How to define database config? - spring

I try to execute simple request to MySql database via jdbcTemplate but I have an error when framework load and parse xml file whicj define my datasource:
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_training"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
</bean>
</beans>
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>SpringTrainingTemplate</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml /WEB-INF/jdbc-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and Controller that invoke it:
#Controller
public class HomeController {
#Autowired
private ExampleService exampleService;
#RequestMapping(value = "/details", method = RequestMethod.GET)
public String details(Model model) {
ApplicationContext context = new ClassPathXmlApplicationContext("jdbc-config.xml");
ExampleDao dao = (ExampleDao) context.getBean("ExampleDao");
List<Application> list = dao.getAllApplications();
model.addAttribute("application", list.get(0).getName());
model.addAttribute("descriptionOfApplication", list.get(0).getDescription());
return "details";
}
}
public class ExampleDao {
private String request = "select * from application";
private JdbcTemplate jdbcTemplate;
#Autowired
private DataSource dataSource;
public ExampleDao(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Application> getAllApplications() {
List<Application> applications = this.jdbcTemplate.query(request, new RowMapper<Application>() {
#Override
public Application mapRow(ResultSet rs, int i) throws SQLException {
Application application = new Application();
application.setName(rs.getString("name"));
application.setType(rs.getString("type"));
application.setDescription(rs.getString("description"));
application.setDownloads(rs.getInt("downloads"));
return application;
}
});
return applications;
}
}
Whe I run it and input http://localhost:8080/details I have got an 500 exception with stacktrace with this message:
root cause
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [jdbc-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [jdbc-config.xml] cannot be opened because it does not exist
Can you explain me how to configure jdbc connection in rigth way or if my approach is correct where I should look for a solution of my issue? All help would be appreciated. Thanks.

Spring cannot find your jdbc-config.xml configuration file.
You can put it in your classpath instead of the WEB-INF folder and load it in your web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml,classpath:jdbc-config.xml</param-value>
</context-param>
A good practice is to create folders main and resources in your src folder and to add them in the classpath. Then you can put the spring config file in the src/resources folder.

class path resource [jdbc-config.xml] cannot be opened because it does
not exist
Is the file name correct, where is it located? the file specifying the db connection is not where you said it should be - on the classpath.

Related

How to use listener-class in spring boot 2.2.1 RELEASE

Migrating Spring web project into spring boot application with following versions
Spring version:-4.1.7
Spring boot:2.2.1 RELEASE
part of migration i need to remove src/main/web-app folder.In this folder i have two files
dispatcher-servlet.xml
web.xml
dispatcher-servlet
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.data.services" />
<bean id="systemPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />
<mvc:interceptors>
<bean class="com.data.services.interceptors.RequestLogInterceptor" />
</mvc:interceptors>
</beans>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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-app_3_0.xsd"
metadata-complete="true" version="3.0">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>XERService</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/conf/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>30000</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>xerwebapp.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.data.services.configuration.ServiceContextListener</listener-class>
</listener>
</web-app>
ServiceContextListener
#WebListener("Service context listener")
public class ServiceContextListener implements ServletContextListener
{
public static final Logger LOG = Logger.getLogger("XERService");
/**
* Context initializer. This method sets the root folder for the log4j
*/
#Override
public void contextInitialized(ServletContextEvent event)
{
}
#Override
public void contextDestroyed(ServletContextEvent event)
{
try
{
LoggingPropertyHandler.clear();
if (XFabSiteConfigManager.getInstance().getRequesterConfigInfo() != null)
{
XFabFactory.getXfabInstance().unInitializeRequester();
}
}
catch (Exception exception)
{
LOG.warn("Exception while uninitializing Requestor", exception);
}
}
}
RequestLogInterceptor
#Component
public class equestLogInterceptor extends HandlerInterceptorAdapter
{
/**
* Method to add the Audit user in the log
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
String auditUser = request.getHeader(RequestParameterConstants.AUDIT_USER);
if (auditUser == null)
{
auditUser = "";
}
LoggingPropertyHandler.addAuditUserName(auditUser);
return true;
}
}
How can we include following listener in spring boot
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.data.services.configuration.ServiceContextListener</listener-class>
</listener>
Is there any simplest mechanism available in spring boot.
You can create the Listener bean like this:
// Register ServletContextListener
#Bean
public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean() {
ServletListenerRegistrationBean<ServletContextListener> bean =
new ServletListenerRegistrationBean<>();
bean.setListener(new MyServletContextListener());
return bean;
}

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.

The requested resource is not available error in spring mvc project

I got an error as follows :
Status report
message: /SBC/loginform.html
description :The requested resource is not available.
dispatcher-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OpticareVisionHouse</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/resources/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
-------------------------------------------------
LoginController.java
#Controller
#RequestMapping("loginform.html")
public class LoginController {
#Autowired
public LoginService loginService;
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
System.out.print("controller calls1");
return "loginform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map model) {
System.out.print("controller calls2");
if (result.hasErrors()) {
return "loginform";
}
/*
String userName = "UserName";
String password = "password";
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUserName().equals(userName)
|| !loginForm.getPassword().equals(password)) {
return "loginform";
}
*/
boolean userExists = loginService.checkLogin(loginForm.getUserName(),
loginForm.getPassword());
if(userExists){
model.put("loginForm", loginForm);
return "loginsuccess";
}else{
result.rejectValue("userName","invaliduser");
return "loginform";
}
}
------------------------------------------------
index.jsp
<% response.sendRedirect("loginform.html"); %>
------------------------------------------------
index.jsp is there at webContent.
loginform.jsp is at webContent->web-Inf ->Views
Your dispatcherServlet is mapping urls like: /forms/* to the spring servlet.
You are requesting a url like: /SBC/loginform.html
This request will never go to the spring servlet. You have to access: /{your app context}/forms/loginform.html in order to go to the spring url mapped. Your app context seems to be "SBC", so it will be something like: /SBC/forms/loginform.html
Another way is change the Servlet mapping to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This way, every request on your app context /SBC/* will be routed to the spring servlet.
With this configuration, you should be able to access your controller with: /SBC/loginform.html

Spring Injection with Servlets: NoSuchBean

New to Spring, and working with Spring 3.2.5 trying to get injection to work with a servlet in a vanilla web app (i.e., it's not a Spring MVC web app - it's a pre-existing app I'm extending using the Spring framework). The container is Tomcat 7.0.47.
My problem is that I'm getting NoSuchBeanDefinitionException errors (No bean named 'MyServlet' is defined) when I hit the servlet. There are no errors at startup, so at least one of my beans (the ServiceImplementation bean) is getting successfully instantiated. The problem appears to be with finding the HttpRequestHandler-derived bean (MyServlet) when a new HTTP request comes in.
The full stack trace for the exception is:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'MyServlet' is defined
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:570)
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1114)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:279)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
org.springframework.web.context.support.HttpRequestHandlerServlet.init(HttpRequestHandlerServlet.java:58)
com.random.webapp.MySpringServlet.init(Unknown Source)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:662)
I followed this pattern for my setup:
http://andykayley.blogspot.com/2008/06/how-to-inject-spring-beans-into.html
...with one minor (I think) twist. I have a class derived from HttpRequestHandlerServlet so that I can override the init method with some application-specific stuff. The extension class looks like this:
public class MySpringServlet extends HttpRequestHandlerServlet
{
public void init() throws ServletException
{
super.init();
appSpecificInit();
}
}
The servlet I want injected looks like this:
public class MyServlet implements HttpRequestHandler
{
private IService _service = null;
public void setService( IService theService ) {
_service = theService;
}
#Override
public void handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
_service.DoSomething();
}
}
The implementation I want it injected with looks like this:
public class ServiceImplementation implements IService
{
#Override
public void DoSomething()
{
// some code goes here
}
}
These are the relevant entries in web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml /WEB-INF/implementation.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.random.webapp.MySpringServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet/*</url-pattern>
</servlet-mapping>
</web-app>
This is the applicationContext.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="MyServlet" class="com.random.webapp.MyServlet">
<property name="Service" ref="ServiceImplementation" />
</bean>
</beans>
...and this is what implementation.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="ServiceImplementation" class="com.random.webapp.ServiceImplementation">
</bean>
</beans>
I've been back and forth between the web.xml, applicationContext.xml, and implementation.xml files to double and triple check my configuration, and I don't see anything wrong with any of them, but I'm obviously missing something.
Anyone have any ideas?
The exception you are getting
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'MyServlet' is defined
occurs in the init() method of the HttpRequestHandlerServlet which tries to load a delegate HttpRequestHandler object from your context based on the name you give the HttpRequestHandlerServlet in your web.xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.random.webapp.MySpringServlet</servlet-class>
</servlet>
In the configuration above, that would be MyServlet. Although it appears you have it correct in
<bean id="MyServlet" class="com.random.webapp.MyServlet">
<property name="Service" ref="ServiceImplementation" />
</bean>
make sure you are loading the correct context file as declared here
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml /WEB-INF/implementation.xml</param-value>
</context-param>

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

Resources