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

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

Related

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

#Autowired is not working in restfull service with spring

This is the mapping part:
#Path("/hello")
public class BookRestController {
#Autowired
BookService service;
#GET
public String getMsg() {
System.out.println("in controller");
List<BookDto> dto=service.loadAll();
System.out.println(dto);
return "dto";
}
}
web.xml code:
<?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>springJdbc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<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>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
servlet-dispatcher.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- controller package detail -->
<context:component-scan base-package="com.app.controller,com.app.service,com.app.dao.hib" />
<!-- -->
<mvc:annotation-driven/>
<!-- -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1500000"/>
<!-- -->
<mvc:resources mapping="/static/**" location="/static/" />
<!-- view resolver -->
<bean id="viewResolver1" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsps/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- creating connection detail of hibernate (connection pooling) -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db1"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- Hibernate mapping and configuration file details (Session factory details) -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.app.entity.BookEntity</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>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
It's giving null pointer exception on service or anything I am using as autowired i.e it's having problems autowiring. Can anyone help with this?I guess i am missing something which is used to implement restFull service coz the application is working fine with simple spring application
Interface :
public interface BookService {
}
Class which implements interface BookService:
#Service
public class BookServiceImpl implements BookService {
}
To autowire BookServiceImpl class, you have to put #Autowired annotation on interface name in BookRestController class and #Controller annotation on your controller class:
#Controller
public class BookRestController {
#Autowired
private BookService bookService;
}
also you have to take care of configuration, like for component scanning you have to add following line in your spring configuration file. Put
<context:component-scan base-package="com.org.dao"/>
in spring configuration xml and change com.org.dao to your package name where dao files placed in application.
This is answered in this thread - Spring DI - Autowired property is null in a REST service
Essentially Jersey doesn't automatically do Spring autowiring for you. You need to get the Spring stuff to happen with the Jersey servlet object.

unable to integrate spring security in existing application

I am not able to find out my problem in spring security integration. I have spent 2-3 days already.So, please help me.
below is my web.xml file
<?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>cdl</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>*.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>startUpServlet</servlet-name>
<servlet-class>com.qait.cdl.commons.startup.StartUpServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>startUpServlet</servlet-name>
<url-pattern>/startUpServlet.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>CDL_ENV</param-name>
<param-value>staging</param-value>
</context-param>
<listener>
<listener-class>com.qait.cdl.commons.startup.CdlContextListner</listener-class>
</listener>
<!-- Session timeout -->
<session-config>
<session-timeout>600</session-timeout>
</session-config>
<!-- <filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/applicationContext.xml
WEB-INF/dispatcher-servlet.xml
</param-value>
</context-param>
</web-app>
Below is my 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" xmlns:p="http://www.springframework.org/schema/p"
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">
<import resource="classapth*:spring/SpringSecurityConfig.xml" />
<!-- <bean name="springSecurityFilterChain" class="org.springframework.web.filter.OncePerRequestFilter"/> -->
</beans>
Below is my SpringSecurityConfig.xml
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/displayAdminPage.htm" access="hasRole('ROLE_ADMIN')" />
<security:form-login login-page="/login.htm" authentication-failure-url="/login.htm"/>
<security:logout logout-url="/logout.htm" logout-success-url="/login.htm"/>
<security:access-denied-handler error-page="/login.htm" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService" >
</security:authentication-provider>
</security:authentication-manager>
below is my 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:p="http://www.springframework.org/schema/p"
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">
<!-- Message resource -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
<value>error</value>
</list>
</property>
</bean>
<!-- Imports all configuration files -->
<import resource="classpath*:spring/*.xml" />
<import resource="classpath*:spring/*/*.xml" />
<!-- Interceptor mapping -->
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<!-- <property name="interceptors" ref="cdlInterceptor" /> -->
<property name="interceptors" ref="cdlSessionInterceptor"></property>
</bean>
<!-- Tiles view resolver and configuration -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order" value="1" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles-defs.xml</value>
</list>
</property>
</bean>
<!-- XmlView Resolver -->
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location" value="/WEB-INF/spring-Xmlviews.xml" />
<property name="order" value="0" />
</bean>
<!-- MultipartResolver for file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="rssViewer" class="com.qait.cdl.rssfeed.view.CustomRssViewer" />
<!-- Default view resolver mapping <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property
name="suffix"> <value>.jsp</value> </property> <property name="order" value="1"
/> </bean> -->
</beans>
I have following queries.
Is it necessary to give "filter" tag in web.xml, if yes than why?
In my application, I have two application context(one for spring security and other for dispatcher-servlet), is it possible for springSecurityConfig.xml to access bean definition which is defined in dispatcher-servlet.xml?
what is the flow of spring-security configuration.Upto my knowledge, i have understood that intercept-url tag intercept the request and check appropriate role using expression language.I am not able to understand how it looks appropriate role in DB via authentication-manager i've provided.
below is my userService bean definition in service.xml
<bean name="userService" class="com.qait.cdl.services.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
below is userService interface
public interface UserService extends UserDetailsService{
}
this UserDetailsService is from springframework
below is UserServiceimpl class
public class UserServiceImpl implements UserService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = null;
if(username != null && !"".equals(username)){
User user = userDao.get(username);
if(user != null){
UserGroupAuthority groupAuthority = userDao.getUserAuthority(user);
if(groupAuthority != null){
Collection<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(groupAuthority.getAuthority());
userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
true, true, true, true, grantedAuthorities);
}
}
}
return userDetails;
}
#Override
public Collection<GrantedAuthority> getGrantedAuthorities(String authority) {
List<GrantedAuthority> grantedAuthorities = new LinkedList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
return grantedAuthorities;
}
#Override
public UserGroupAuthority getUserAuthority(User user) {
return userDao.getUserAuthority(user);
}
}
Simply the problem is , it is not validating the given intercept-url. Where I am doing mistake?
Activate springSecurityFilterChain in your web.xml. It's an entry point of Spring Security. If springSecurityFilterChain is deactivated then Spring Security will never work.

Spring #Transactional not creating transactions

I am seriously beating my head against a wall with Spring transactions. I have searched for days trying to get #Transactional to work. Any help would GREATLY appreciated!
I am using Spring 3.2 for a web app accessing a MySQL database (I'm using Spring MVC, JDBC, and Security). The mysql tables are using InnoDB. I'm struggling to get declarative transactions to work (I tried using programmatic transactions and that worked successfully). I have controllers calling service methods that are annotated with #Transactional. The controllers are configured in the servlet xml file and the services/dao's are configued in a separate application xml file. I cannot seem to find the right configuration for #Transactional to be picked up and create transactions. There are no errors - just no transactioning. Here are the details of my setup:
Web application using DispatcherServlet, configured with a servlet XML file, using annotated controllers. Controllers have Service interfaces injected.
Service methods are annotated with #Transactional and call injected DAO classes.
Service classes are annotated with #Named, and the app is configured to pick these up in spring-app-context.xml using component-scan.
Transactioning configuration is setup in spring-app-context.xml (not in the servlet configuration file).
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-app-context.xml
/WEB-INF/config/spring-security-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-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: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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="ewarrants.web" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:property-placeholder location="/WEB-INF/config/ewarrants.properties"/>
</beans>
Here is a sample controller setup:
#Inject
IUserService userService;
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String processRegistration(#Valid #ModelAttribute UserRegistrationVM incomingVM, BindingResult result, Model model) throws Exception {
...
userService.registerNewUser(newUser);
return "redirect:<location>";
}
Here is spring-app-context:
<?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"
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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="ewarrants.core" />
<tx:annotation-driven transaction-manager="txManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="<url>"/>
<property name="username" value="<user>"/>
<property name="password" value="<password>"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<context:property-placeholder location="/WEB-INF/config/ewarrants.properties"/>
</beans>
Here is a sample service implementation:
#Named
public class UserService extends Service implements IUserService {
#Inject
private IUserDao userDao;
#Override
#Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void registerNewUser(User user) throws Exception {
...
// add the user record
int newUserID = userDao.insertUser(user);
// carry out more database inserts
}
}

Spring MVC + Hibernate 4 + Spring Security

I have been struggling to make all of this work since days now and don't know what to do. I believe I went through every single post on the subject here on SO and went through douzens of tutorials...
Here is the message I am having at this time:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fruitController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.controller.FruitController.setFruitManager(com.service.FruitManager); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.service.FruitManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I have been able to solve this error in the past, but only to have a new one "No session found for current thread". When not having this one, I got some problem with my Assembler and UserDetailsServiceImpl bean not being recognized in my spring-security.xml file...
I do not think the problem(s) come from my code, I just can't get to set my config files properly and I am probably missing something here.
Here are the config files:
web.xml:
<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>Spring MVC Application</display-name>
<!-- Spring MVC -->
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<!-- Load everything except #Controllers -->
<context:component-scan base-package="com">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="save*" />
<tx:method name="*" read-only="false" />
</tx:attributes>
</tx:advice>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.dao.HibernateFruitDAO</value>
</list>
</property>
<property name="packagesToScan">
<list>
<value>com.service</value>
<value>com.controller</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<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/basename" />
<property name="username" value="xxx" />
<property name="password" value="yyy" />
</bean>
</beans>
mvc-dispatcher-servlet.xml:
<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"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath:hibernate.properties" />
<!-- Load #Controllers only -->
<context:component-scan base-package="com.controller"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<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="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
</beans>
spring-security.xml
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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<beans:bean id="userDetailsService" class="com.service.UserDetailsServiceImpl">
</beans:bean>
<beans:bean id="assembler" class="com.service.Assembler">
</beans:bean>
<http auto-config='true' use-expressions='true'>
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/secure/**" access="hasRole('ROLE_Admin')" />
<logout logout-success-url="/listing.htm" />
<form-login login-page="/login.htm" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login_error.htm" default-target-url="/listing.htm"
always-use-default-target="true" />
</http>
<beans:bean id="com.daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="com.daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
</beans:beans>
FruitController:
package com.controller;
#Controller
public class FruitController{
protected final Log logger = LogFactory.getLog(getClass());
private FruitManager fruitManager;
#Autowired
public void setFruitManager(FruitManager FruitManager) {
this.fruitManager = fruitManager;
}
#RequestMapping(value = "/listing", method = RequestMethod.GET)
public String getFruits(ModelMap model) {
model.addAttribute("fruits", this.fruitManager.getFruits());
return "listing";
}
}
FruitDAO:
public interface FruitDAO {
public List<Fruit> getFruitList();
public List<Fruit> getFruitListByUserId(String userId);
public void saveFruit(Fruitprod);
public void updateFruit(Fruitprod);
public void deleteFruit(int id);
public Fruit getFruitById(int id);
}
HibernateFruitDAO
package com.dao;
#Repository("fruitDao")
public class HibernateFruitDAO implements FruitDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Fruit> getList() {
return (List<Fruit>) getSession().createCriteria ( Fruit.class ).list();
}
public List<Fruit> getFruitListByUserId(String userId) {
return (List<Fruit>)sessionFactory.getCurrentSession().createCriteria("from Fruit where userId =?", userId).list();
}
public void saveFruit(Fruit fruit) {
sessionFactory.getCurrentSession().save(fruit);
}
public void updateFruit(Fruit fruit) {
sessionFactory.getCurrentSession().update(fruit);
}
public void deleteFruit(int id) {
Fruit fruit = (Fruit) sessionFactory.getCurrentSession().load(Fruit.class, id);
if (null != fruit) {
sessionFactory.getCurrentSession().delete(fruit);
}
}
public Fruit getFruitById(int id) {
return (Fruit)sessionFactory.getCurrentSession().load(Fruit.class, id);
}
private Session getSession(){
return sessionFactory.getCurrentSession();
}
}
Interface FruitManager:
package com.service;
import java.io.Serializable;
import java.util.List;
import com.domain.Fruit;
public interface FruitManager extends Serializable{
public List<Fruit> getFruits();
public List<Fruit> getFruitsByUserId(String userId);
public void addFruit(Fruit fruit);
public void removeFruit(int id);
public Fruit getFruitById(int id);
public void updateFruit(Fruit fruit);
}
Implementation of FruitManager:
package com.service;
#Repository("fruitManager")
#Transactional
public class SimpleFruitManager implements FruitManager {
/**
*
*/
private static final long serialVersionUID = ...;
#Autowired
private FruitDAO fruitDao;
public List<Fruit> getFruits() {
return fruitDao.getFruitList();
}
public List<Fruit> getFruitsByUserId(String userId){
return fruitDao.getFruitListByUserId(userId);
}
public void setFruitDao(FruitDAO fruitDao) {
this.fruitDao = fruitDao;
}
public void addFruit(Fruit fruit) {
fruitDao.saveFruit(fruit);
}
public void removeFruit(int id) {
fruitDao.deleteFruit(id);
}
public getFruitById(int id) {
return fruitDao.getFruitById(id);
}
public void updateFruit(Fruit fruit) {
fruitDao.updateFruit(fruit);
}
}
At a glance, it seems you're suffering from a common problem of not understanding how Spring ApplicationContexts fit together to make a web application. See my other answer to exactly the same problem to see if it clears things up:
Declaring Spring Bean in Parent Context vs Child Context
You may also be enlightened by this answer on a similar topic, which links to my previously mentioned answer as well as one other:
Spring XML file configuration hierarchy help/explanation
A couple brief tips to get you headed in the right direction...
By convention, Spring's ContextLoaderListener loads beans from WEB-INF/applicationContext.xml to create the root application context. When you override the default, as you're doing, that file is no longer loaded.
Tip #1: stick with the conventional behavior. It'll make your life simpler.
Also by convention, starting up a Spring DispatcherServlet loads beans from WEB-INF/<servlet name>-context.xml to create the context used to configure the dispatcher servlet. This context becomes a child of the root context.
Tip #2: see tip #1
So you see, you're presently over-configuring things. Read the linked answers and the reference materials linked therein. Learn to work with Spring instead of against it.
In your web.xml file, the applicationContext.xml is never get loaded. You should put it location in context-param. Put the location of mvc-dispatcher-servlet.xml (containing controller related bean) as init-param for DispatcherServlet instead:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
I think you must to use this in the DaoImpl to get the session:
#Autowired
private SessionFactory sessionFactory;

Resources