error in xml files in spring mvc - spring

I have three xml files for the spring project as follows
application-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema
/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-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">
<context:annotation-config/>
<bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/indi" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
CController-servlet.xml(It is manager level 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema
/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-2.0.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="project4"/>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean name="frm4" class="project4.CController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
and UUController-servlet.xml(this is a dao level 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema
/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema
/context/spring-context-2.5.xsd">
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="project4"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="project4.UserDAOImpl1">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
i have two xml files one for manager call and another for dao call...i know ref link from one xml points to the bean in another xml.I thought they will automatically link but i am getting the following error
Error creating bean with name
'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0'
defined in ServletContext resource [/WEB-INF/CController-servlet.xml]: Initialization
of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'frm4' defined in ServletContext resource [/WEB-INF/CController-servlet.xml]: Cannot
resolve reference to bean 'myUserDAO' while setting bean property 'userDAO'; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'myUserDAO' is defined
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'frm4' defined in ServletContext resource [/WEB-INF/CController-
servlet.xml]: Cannot resolve reference to bean 'myUserDAO' while setting bean property
'userDAO'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named
'myUserDAO' is defined
UserDAOImpl1 is my hibernate template class and CCController is my spring controller class
CCController.java
package project4;
import project4.UserDAO1;
import project4.User1;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
#Controller
#RequestMapping("frm4.do")
public class CController{
private UserDAO1 userDAO;
public void setUserDAO(UserDAO1 userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "/add", method = RequestMethod.POST)
public ModelAndView add( #ModelAttribute("add") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.saveUser(user);
System.out.println("hai");
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "delete", method = RequestMethod.POST)
#Transactional
public ModelAndView delete(#ModelAttribute("delete") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.deleteUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "find", method = RequestMethod.POST)
#Transactional
public ModelAndView find(#ModelAttribute("find") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.findUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "update", method = RequestMethod.POST)
#Transactional
public ModelAndView update(#ModelAttribute("update") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.updateUser(user);
return new ModelAndView("redirect:list.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("user", new User1());
return new ModelAndView("userForm", modelMap);
}
}
can someone help plz
EDIT:
the web.xml is as follows
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<servlet>
<servlet-name>CController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

frm4 bean has a property which has reference to userDAO, which is declared in other xml file. So make sure all the xml files are loaded in application context. To do this you need to add all the xml files in web.xml.
Try this :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/UUController-servlet.xml,
/WEB-INF/application-context.xml,
/WEB-INF/CController-servlet.xml
</param-value>
</context-param>
EDIT :
If this is not working for you. Try adding other files in application-context.xml file. Use bean import tag.
<beans:import resource="/WEB-INF/UUController-servlet.xml"/>
<beans:import resource="/WEB-INF/CController-servlet.xml"/>
And load only application-context file at startup.
EDIT :
The reason behind the error 'Cannot map handler' is that you are scanning components at application startup and also having the same bean declared in application context.
<context:component-scan base-package="project4"/>
&
<bean name="frm4" class="project4.CController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
Remove bean declaration from xml file since you already have scanned that particular component. And autowire myUserDAO bean in you controller class.
#Autowire
#Qualifier("myUserDAO")
private UserDAOImpl1 myUserDAO;

The problem is the UUController-servlet file is not loaded by the application context. Since it is a db level context add this to contextConfigLocation as shown below. Also I would recommend renaming it to dao-context.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
/WEB-INF/UUController-servlet.xml
</param-value>
</context-param>

Related

java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver

i have a problem about Bean creation in xml definer.
When i run the application on server it shows me the first page but when i go to /customer/list it gives me http error - 500
In the tutorial he does nothing else of what i've done.
I can't show you all the .JAR files in the LIB but i have all the dependency he has in the tutorial example.
I am not using Maven, its a normal Dynamic Web Project so i can't just pass to Maven Project.
I've tried to change the Bean name trying to understand if it was a problem of existing object.
This is my Servlet:
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
String driver = "com.mysql.cj.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
This is my CustomerController:
package com.luv2code.springdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping("/list")
public String listCustomer(Model theModel) {
return "list-customer";
}
}
This is my definer.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC;allowPublicKeyRetrieval=true" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
and this is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-crud-demo</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The exception encountered is:
*org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver *
java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.Environment *
You could try to add this jar to your project net.bytebuddy.
But I recommend to use maven for these purposes.

Spring 4 JDBC - How to load DB Properties and optimize (using Cache or DB Connection Pool)

Am maintaining a codebase which was written in Spring MVC 4.3.9.RELEASE (not Spring Boot)...
Under src/main/resources:
There are two different database configuration files:
sampledb.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"
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">
<!-- Initialization for data source dbcp -->
<bean id="sampleDatabase" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost/sampledb?zeroDateTimeBehavior=convertToNull</value></property>
<property name="username"><value>root/value></property>
<property name="password"><value></value></property>
<property name="maxIdle" value="10"/>
<property name="maxActive" value="50"/>
<property name="maxWait" value="100"/>
<property name="defaultAutoCommit" value="false"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="1"/>
<property name="minIdle" value="0"></property>
<property name="timeBetweenEvictionRunsMillis" value="1000"></property>
<property name="minEvictableIdleTimeMillis" value="1000"></property>
</bean>
</beans>
eventsdb.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"
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">
<!-- Initialization for data source dbcp -->
<bean id="eventsDatabase" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost/eventsdb?zeroDateTimeBehavior=convertToNull</value></property>
<property name="username"><value>root</value></property>
<property name="password"><value></value></property>
<property name="maxIdle" value="10"/>
<property name="maxActive" value="50"/>
<property name="maxWait" value="100"/>
<property name="defaultAutoCommit" value="false"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="1"/>
<property name="minIdle" value="0"></property>
<property name="timeBetweenEvictionRunsMillis" value="1000"></property>
<property name="minEvictableIdleTimeMillis" value="1000"></property>
</bean>
</beans>
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>MyApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
WEB-INF/mvc-dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com.myapp.rest.controllers" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Sample webservice code:
package com.myapp.rest.controllers;
#Controller
#RequestMapping("/v2")
public class MyController {
#RequestMapping(value="users/{userId}",method=RequestMethod.GET)
public #ResponseBody Object getUserDetails(#PathVariable String userId){
Object response=null;
UserDAO dao = UserDAO.getInstance();
response=dao.getUser(userId);
return response;
}
}
UserDao:
public class UserDAO {
private static UserDAO instance = null;
private JdbcTemplate jdbcTemplateObject = null;
public static UserDAO getInstance() {
if(instance == null) {
synchronized(UserDAO.class) {
if(instance == null) {
instance = new UserDAO();
}
}
}
return instance ;
}
UserDAO() {
try {
initializeDB();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void initializeDB() {
try {
ApplicationContext context = new ClassPathXmlApplicationContext("sampledb.xml");
DataSource dataSource = (DataSource) context.getBean("sampleDatabase");
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
catch (Exception e) {
e.printStackTrace();
}
}
// others methods which do the actual queries using Spring JDBC
}
The previous author has used this pattern (initializing the DB using ApplicationContext) in every single DAO (there's like 20 different ones in the codebase each doing the same thing with the same two database config files)!
Question(s):
This seems very inadequate (seems like should be done once), how can this (loading Spring based DB config files) be done once as soon as the war file loadings into Tomcat?
What's the best techniques for performance gains (e.g. should I use a caching system or a database connection pool)?
Any advice is greatly appreciated...
private void initializeDB() {
try {
ApplicationContext context = new ClassPathXmlApplicationContext("sampledb.xml");
DataSource dataSource = (DataSource) context.getBean("sampleDatabase");
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
catch (Exception e) {
e.printStackTrace();
}
}
This code is very dangerous, depending on the size of your context, you eventually will run into issues. What happens here is you are loading the whole application each time you need an object, you will open up connections to the db (which eventually will stop working due to too many connections) you will have weird transaction issues and probably (depending on the size) memory issues. (Of course if that is what you want by all means proceed like this).
Instead you should be using dependency injection. Declare all needed dependencies as fields and let spring do the auto wiring, which will happen just once at startup.
#Controller
#RequestMapping("/v2")
public class MyController {
private final UserDAO dao;
#Autowired
public MyController(UserDAO Dao) {
this.dao=dao;
}
#RequestMapping(value="users/{userId}",method=RequestMethod.GET)
public #ResponseBody Object getUserDetails(#PathVariable String userId){
return dao.getUser(userId);;
}
}
In your UserDAO do something like this.
#Repository
public class UserDAO {
private final JdbcTemplate jdbcTemplate;
#Autowired
public UserDAO(#Qualifier("sampleDatabase") DataSource dataSource) {
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
// others methods which do the actual queries using Spring JDBC
}
Another thing is in your web.xml you both have a ContextLoaderListener and DispatcherServlet. Now this doesn't have to be a problem but in your case both classes load the same application context resulting in your application being loaded twice with one instance doing nothing.
Remove the ContextLoaderListener and the context-param from your web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>MyApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Now in your mvc-dispatcher-servlet.xml add the following 2 lines.
<import resource="classpath:sampledb.xml" />
<import resource="classpath:eventsdb.xml" />
Or move the contents of both files to the mvc-dispatcher-servlet.xml.
You can use a JNDI Configuration its the best practices between you App and Tomcat :
in your xml configuration :
<jee:jndi-lookup id="sampleDatabase" jndi-name="jdbc/sampleDatabase" />
<bean id="sampleDatabaseJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="sampleDatabase" />
<property name="resultsMapCaseInsensitive" value="true" />
<property name="nativeJdbcExtractor" ref="nativeJdbcExtractor" />
</bean>
on your tomcat server.xml you can add below resource under <GlobalNamingResources>
<Resource name="jdbc/sampleDatabase" auth="Container" global="jdbc/sampleDatabase" type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/sampledb"
username="root" password="" maxActive="50" maxWait="-1" maxIdle="10"
validationQuery="SELECT 1 FROM DUAL" testOnBorrow="TRUE" />
on tomcat context.xml :
<ResourceLink auth="Container" global="jdbc/sampleDatabase" name="jdbc/sampleDatabase" type="javax.sql.DataSource"/>
and on you UserDAO :
.....
#Autowired
#Qualifier("sampleDatabaseJdbcTemplate")
private JdbcTemplate sampleDatabaseJdbcTemplate;
...
you can do the same config for the second Database

#Transactional not working using spring mvc and hibernate

I have tried a lot but #Transactional is still not working.
I have refereed a lot but i still didn't find any proper answers
I want to insert the same record in two different tables with do everything or nothing principle.
Means that if problem occurs while inserting data in one table then it must rollback from the already inserted table. So data must be inserted or rollbacked in both tables for any problem.
Please anyone help me...
package com.cds.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.cds.service.SaveEmployeeService;
import com.cds.vo.EmployeeVo;
#Controller
public class SpringHibernateController {
#Autowired
SaveEmployeeService saveEmployeeService;
#RequestMapping("home")
public String showHomePage(){
return "home";
}
#RequestMapping("form")
public String showFormPage(){
return "form";
}
#RequestMapping("submit")
public String saveEmployeeFromData(#ModelAttribute("employee") EmployeeVo employeeVo,RedirectAttributes redirectAttributes){
try{
saveEmployeeService.saveEmployeeAndCustomer(employeeVo);
redirectAttributes.addFlashAttribute("success","Saved In Both Tables Successfully");
}catch(Exception e){
e.printStackTrace();
redirectAttributes.addFlashAttribute("unsuccess","Unable To Save In Both Tables.. Please Try Again");
}
return "redirect:form";
}
}
This is my service class which contains method that will insert the same records in two tables using #Transactional but its not working
#Service
public class SaveEmployeeServiceImpl implements SaveEmployeeService{
#Autowired
SaveEmployeeDAO saveEmployeeDAO;
#Transactional(propagation=Propagation.REQUIRED)
public void saveEmployeeAndCustomer(EmployeeVo employeeVo){
int saveEmployee = saveEmployee(employeeVo);
int saveCustomer = saveCustomer(employeeVo);
if(saveEmployee==1 && saveCustomer==1){
System.out.println("saved In both table successfully");
}else{
throw new RuntimeException();
}
}
public int saveEmployee(EmployeeVo employeeVo) {
Employee employee=null;
try {
employee=new Employee();
employee.setName(employeeVo.getName());
employee.setJobtitle(employeeVo.getJobtitle());
employee.setSalary(Integer.parseInt(employeeVo.getSalary()));
employee.setPassword(Integer.parseInt(employeeVo.getPassword()));
employee.setPhoto(employeeVo.getPhoto().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return saveEmployeeDAO.saveEmployee(employee);
}
public int saveCustomer(EmployeeVo employeeVo) {
int a=10/0;
Customer cutomer=null;
try {
cutomer=new Customer();
cutomer.setName(employeeVo.getName());
cutomer.setJobtitle(employeeVo.getJobtitle());
cutomer.setSalary(Integer.parseInt(employeeVo.getSalary()));
cutomer.setPassword(Integer.parseInt(employeeVo.getPassword()));
cutomer.setPhoto(employeeVo.getPhoto().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return saveEmployeeDAO.saveCustomer(cutomer);
}
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" version="3.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
</web-app>
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!--
<context:component-scan base-package="com.cds">
<context:exclude-filter type="regex" expression="com.cds.controller.*"/>
</context:component-scan>
-->
//I have tried with above scan also but still its not working
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="admin"></property>
<property name="acquireIncrement" value="5" />
<property name="initialPoolSize" value="20"></property>
<property name="maxPoolSize" value="1000"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.cds.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>
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"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.cds.controller"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/pages/</value></property>
<property name="suffix"> <value>.jsp</value></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
</beans>

Spring MyBatis expected at least 1 bean which qualifies as autowire candidate for this dependency

i have a trouble with my Spring MyBatis Project.
Here the classes of the 4 packages tiers:
controller
mapper
model
service
com.mb.alf.controller
ServizioController.java
package com.mb.alf.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.mb.alf.model.Servizio;
import com.mb.alf.service.ServizioService;
#Controller
#SessionAttributes("servizio")
public class ServizioController {
#Autowired
private ServizioService servizioService;
#RequestMapping("/returnServizio")
public ModelAndView returnServizio() {
Servizio servizio = servizioService.getServizio();
return new ModelAndView("returnServizio", "servizio", servizio); }}
com.mb.alf.mapper
ServizioMapper.java
package com.mb.alf.mapper;
import org.apache.ibatis.annotations.Select;
import com.mb.alf.model.Servizio;
public interface ServizioMapper {
#Select("select s.ser_puntopresa, s.ser_oldcodser from serviz s where s.ser_ute = '01' and S.SER_PUNTOPRESA = 101")
public Servizio getServizio();
}
com.mb.alf.model
Servizio.java
package com.mb.alf.model;
public class Servizio {
Integer serv_puntopresa;
Integer ser_oldcodser;
public Integer getSer_oldcodser() {
return ser_oldcodser; }
public void setSer_oldcodser(Integer ser_oldcodser) {
this.ser_oldcodser = ser_oldcodser; }
public Integer getServ_puntopresa() {
return serv_puntopresa; }
public void setServ_puntopresa(Integer num) {
this.serv_puntopresa = num; }
}
com.mb.alf.service
ServizioService.java
package com.mb.alf.service;
import com.mb.alf.model.Servizio;
public interface ServizioService {
Servizio getServizio();
}
ServizioServiceImpl.java
package com.mb.alf.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mb.alf.mapper.ServizioMapper;
import com.mb.alf.model.Servizio;
#Component #Service("servizioService")
public class ServizioServiceImpl implements ServizioService {
#Autowired
private ServizioMapper servizioMapper;
#Transactional
public Servizio getServizio() {
return servizioMapper.getServizio(); } }
Here my XML files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<servlet>
<servlet-name>myBatisServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myBatisServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<display-name>Archetype Created Web Application</display-name>
</web-app>
springConfig.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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.mb.alf" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#MYHOST:orcl"/>
<property name="username" value="USER"/>
<property name="password" value="PASSWORD"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.mb.alf.model"/>
<property name="mapperLocations" value="classpath*:com/mb/alf/mapper/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mb.alf.mappers" />
</bean>
</beans>
It gets this Exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servizioController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mb.alf.service.ServizioService com.mb.alf.controller.ServizioController.servizioService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servizioService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mb.alf.mapper.ServizioMapper com.mb.alf.service.ServizioServiceImpl.servizioMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mb.alf.mapper.ServizioMapper] 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)}
Please, how and where can I implement the correct bean?
Thanks in advance
Perhaps you should seperate the mybatis setup in another xml instead of putting it in current springConfig.xml
For example:
web.xml add the following:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring.xml;
classpath:conf/spring-mybatis.xml
</param-value>
</context-param>
...
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In spring-mybatis.xml*, add your dataSource, transactionManager, sqlSessionFactory, sqlSession and org.mybatis.spring.mapper.MapperScannerConfigurer.
One example can be found here https://github.com/liratanak/SpdSample-Spring-MVC-3-MyBatis-3-Tiles-3

Why Service not injected in Controller with Spring?

I have a problem with a controller and a service injection. In Junit test, it is working all data are added in database and no errors return by my test junit. But when I inject the Service in the Controller, the system return a null object instead instantiation :
My service :
package mypackage.services
public interface ExampleService {
public abstract String helloWorld();
}
package mypackage.services;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
#Service("exampleService")
#Scope("singleton")
public class ExampleServiceImpl implements ExampleService {
#Override
public String helloWorld(){
return "Hello World !";
}
}
My Controller:
package mypackage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/planning")
public class PlanningController {
#Autowired
public ExampleService exampleService;
#RequestMapping(method = RequestMethod.GET)
public final ModelAndView planning(final HttpServletRequest request) {
exampleService.helloWorld();
final ModelAndView mav = new ModelAndView("planning", "tasks", "tasks");
return mav;
}
}
Spring-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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Use #Component annotations for bean definitions -->
<context:component-scan base-package="mypackage.services" />
<context:component-scan base-package="mypackage.controller" />
<!-- Use #Controller annotations for MVC controller definitions -->
<mvc:annotation-driven />
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- View resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- Renders JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<mvc:interceptors>
<!-- Resolve the device that originated the web request -->
<bean
class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
</mvc:interceptors>
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDatasource" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="database" value="ORACLE" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.c3p0.maxSize">1</prop>
<prop key="hibernate.c3p0.minSize">1</prop>
<prop key="hibernate.c3p0.acquireIncrement">1</prop>
<prop key="hibernate.c3p0.idleTestPeriod">300</prop>
<prop key="hibernate.c3p0.maxStatements">0</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.checkoutTimeout">0</prop>
<prop key="hibernate.c3p0.preferredTestQuery">SELECT * FROM dual</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
and my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<resource-ref>
<description>My DataSource Reference</description>
<res-ref-name>jdbc/myDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
My test :
...
#Autowired
private ApplicationContext applicationContext;
#Test
public void testPlanning() {
LOGGER.debug("Start testPlanning");
boolean c = applicationContext.containsBean("exampleService");
System.out.println(c);
final PlanningController avc = new PlanningController();
final Object mav = avc.planning(request);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(mav instanceof ModelAndView);
ModelAndViewAssert.assertViewName((ModelAndView) mav, "planning");
final BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
LOGGER.debug("End testPlanning");
}
I inherit from a class for my test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-servlet.xml"})
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
public abstract class N2WIAppConfigTest {
private static final Logger LOGGER = LoggerFactory
.getLogger(PlanningControllerTest.class);
#BeforeClass
public static void setUpClass() throws Exception {
// rcarver - setup the jndi context and the datasource
LOGGER.debug("CALL setUpClass");
try {
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder
.emptyActivatedContextBuilder();
// Construct DataSource
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("oracle.jdbc.driver.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:#localhost:1521:xe");
ds.setUser("nemo2");
ds.setPassword("nemo2");
builder.bind("java:comp/env/jdbc/myDatasource", ds);
builder.activate();
} catch (NamingException ex) {
System.out.println("###################################");
ex.printStackTrace();
}
}
}
I tried in my test load the ApplicationContext and if the service is loaded and it is the case. But in the PlanningController, the service is not injected.
The problem occurs in PlanningController. ExampleService is not injected and don't understand why. Do you have any idea ?
Thanks a lot
For #Autowire to work there are set of things that we need to configure
<context:annotation-config /> in context.xml, You are missing this.
xmlns:context="http://www.springframework.org/schema/context in <beans .. tag
Spring Sterio type annotations like #Controller, #Component, #Service etc.
That's because in this line:
final PlanningController avc = new PlanningController();
you are manually creating a bean instance instead of leaving it to spring, so spring has no means to autowire dependencies.
You should either leave bean creation to the container (spring in this case) or set bean properties yourself.
In your case, you can access spring-managed PlanningController instance using
applicationContext.getBean(PlanningController.class);

Resources