Spring MVC + Hibernate 4 + Spring Security - spring

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;

Related

entity manager not correctly injected by spring and gives java.lang.NullPointerException [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
I'm a newbie at using frameworks in JAVA EE
so when I'm trying to call a method of the entity manager
it throws a java.lang.NullPointerException
so I want to what I wrote
this is an example of my dao implementation
#Repository
#Transactional
public class IUserDAOImpl implements IUserDAO{
#PersistenceContext
private EntityManager em;
public void addUser(User u) {
em.persist(u);
}
}
this is my service
#Service
public class IUserServiceImpl implements IUserService {
#Autowired
private IUserDAO dao = new IUserDAOImpl();
public void setDao(IUserDAO dao) {
this.dao = dao;
}
public void addUser(User u) {
dao.addUser(u);
}
this is my action class
public class ConnectionAction extends ActionSupport {
User c = new User("a","b","c",11,"d",true);
#Autowired
public IUserService service;
public String execute() throws Exception {
service.addUser(c);
return SUCCESS;
}
the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" 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>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
the applicationContext.xml (although it's really messed up so if you noticed sometihng wrong plz tell)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:tx="http://www.springframework.org/schema/tx" 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: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/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="dao"
class="com.iticsys.GBO.dao.IUserDAOImpl">
</bean>
<bean id="service"
class="com.iticsys.GBO.services.IUserServiceImpl">
<property name="dao" ref="dao"></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/GBO1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<value>classpath*:META-INF/persistence.xml</value>
</property>
<property name="defaultDataSource" ref="dataSource"> </property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.iticsys.GBO.dao" />
</beans>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/GBO1" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
and thank you so much in advance
In implementation of class IUserDAOImpl you should instantiate the Object of EntityManager like
private EntityManager em = new EntityManager(/*constructor parameter if any*/);
or You can assign a reference of Object of EntityManager that you can create in your other subclasses like IUserServiceImpl, ConnectionAction.
For that you can add a method in your class IUserDAOImpl which receive that reference.like,
public void setEntityManager(EntityManager em_ref ){ em = em_ref;}
public class HibernateUtil {
static Logger logger = Logger.getLogger(HibernateUtil.class);
private static final String FAILED_TO_CREATE_SESSION_FACTORY_OBJECT = "Failed to create sessionFactory object.";
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("./hibernate.cfg.xml");
configuration.addAnnotatedClass(Calzz.class);
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
logger.debug(FAILED_TO_CREATE_SESSION_FACTORY_OBJECT + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Cannot autowire Spring Data Repository

I'm creating a simple application with Spring, Hibernate and MySQL database. I've done some research, but no answer was accurate. I have a repository interface, which is an extension of BaseCrudRepository, which extends ReadOnlyRepository, which is an extension of org.springframework.data.repository.Repository.
Code is as below:
package dziecko.repositories;
import dziecko.models.AreaDate;
import dziecko.utils.BaseCrudRepository;
public interface AreaDateRepository extends BaseCrudRepository<AreaDate, Integer> {}
AreaDate is a simple entity:
#Entity
#Table(name = "AREADATES")
public class AreaDate extends AbstractBase implements DtoGenerator<AreaDateDto> {
private static final long serialVersionUID = -2956040373671316338L;
#Column(name = "START_TIME")
private Date startTime;
#Column(name = "END_TIME")
private Date endTime;
#Column(name = "ALARM", nullable = true)
private Boolean alarm;
public AreaDate() {
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Boolean getAlarm() {
return alarm;
}
#Override
public AreaDateDto createDto() {
return new AreaDateDto(id, startTime, endTime, alarm);
}
}
Here 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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
app-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:beans="http://www.springframework.org/schema/beans" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<jpa:repositories base-package="dziecko.repositories" />
<context:annotation-config />
<!-- Scan classpath for annotations (eg: #Service, #Repository etc) -->
<context:component-scan base-package="dziecko.rests, dziecko.services">
<context:exclude-filter expression="org.springframework.web.bind.annotation.RestController" type="annotation" />
</context:component-scan>
<!-- JDBC Data Source. -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/dziecko" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<!-- Hibernate Session Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan">
<array>
<value>dziecko.models</value>
</array>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="jadira.usertype.autoRegisterUserTypes">true</prop>
<prop key="jadira.usertype.databaseZone">jvm</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
The problem is that even this simple test fails, because repository which is supposed to be autowired is null:
package dziecko.tests;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;
import dziecko.repositories.AreaDateRepository;
public class SpringConfigurationTest {
#Autowired
private AreaDateRepository adRepo;
#Test
public void shouldWireComponents() {
Assert.assertNotNull(adRepo);
}
}
java.lang.AssertionError: expected object to not be null
All entities are created inside the database. I just can't figure out how to configure those Spring repositories properly. Everything seems to be done similar to http://docs.spring.io/spring-data/data-commons/docs/1.5.1.RELEASE/reference/html/repositories.html. Anyone has an idea how autowiring can be fixed here?
This is happening because your test class is Spring unaware. You need to:
include spring-test jar in your (test) classpath via Maven dependency or other means
From your test I can see you are using TestNG so the above jar will make for you available the TestNG Spring test runner:
Annotate your class with (supposing you don't have test context. That would have been a better practice btw):
#ContextConfiguration(locations = { "classpath:app-context.xml" })
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests
{
//...
}
So I had app-context.xml file in WEB-INF folder and I didn't attach this context to test. Working version:
#ContextConfiguration("/META-INF/app-context.xml")
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests {
#Autowired
private AreaDateRepository adRepo;
#Test
public void shouldWireComponents() {
Assert.assertNotNull(adRepo);
}
}

get Null pointer Exception when try to access model class in dwr function

My SessionFactory object is #Autowired
package com.ravi.dao.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ravi.dao.UserDao;
import com.ravi.model.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<User> listUsers()
{
System.out.println("UserDaoImpl - listUsers");
return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
}
#Override
public void saveUser(User user)
{
System.out.println("UserDaoImpl - saveUser");
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUserByUserEmail(String userEmail)
{
System.out.println("UserDaoImpl - getUserByUserEmail");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list();
}
#SuppressWarnings("unchecked")
#Override
public List<User> validateLoginUser(String userEmail, String password)
{
System.out.println("userEmail -- "+userEmail+" password --"+password);
System.out.println("UserDaoImpl - validateLoginUser");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail and password=:password").setString("userEmail", userEmail).setString("password",password).list();
}
}
i create on dwr function which is below.
package com.ravi.dwr;
import java.util.List;
import com.ravi.dao.daoImpl.UserDaoImpl;
import com.ravi.model.User;
public class ForgotPwd
{
public void sendMail(String EmailId)
{
System.out.println("DWR Called.");
UserDaoImpl userDaoImpl=new UserDaoImpl();
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
User user=lstUser.get(0);
System.out.println("DWR Called.-- userEmail :"+user.getUserEmail());
}
}
when i want to try to print userEmail . null pointer exception is generated # return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list(); this point.
my spring-servlet.xml cofiguration.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.ravi"/>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- <bean id="sessionFactory" -->
<!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ravi.model.User</value>
<value>com.ravi.model.Language</value>
<value>com.ravi.model.Questions</value>
<value>com.ravi.model.QuestionOptions</value>
<value>com.ravi.model.Admin</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="SessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
i don't want to remove #Autowired annotation in sessionFactory object. so please suggest me the best way to access or configure dwr function. other way i tried without using #Autowired annotation but in that case i have to entry all bean class in my spring-servlet.xml and also configure. hibernate.cfg.xml file.
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
UserLoginController --> showUserLogin
INFO (org.directwebremoting.log.startup:157) - Starting: DwrServlet v3.0.0-RC2-final-312 on Apache Tomcat/7.0.50 / JDK 1.7.0_10 from Oracle Corporation at `enter code here`/OnlineQuestion
DWR Called.
INFO (org.directwebremoting.log.accessLog:427) - Method execution failed:
java.lang.NullPointerException
at com.ravi.dwr.ForgotPwd.sendMail(ForgotPwd.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChai
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
Assuming you want to use Spring MVC with DWR, try following code:
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
...
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
...
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<dwr:controller id="dwrController" />
<dwr:annotation-scan base-package="com.ravi.dwr" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.ravi" />
...
</beans>
ForgotPwd.java
package com.ravi.dwr;
...
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
...
#RemoteProxy
public class ForgotPwd {
#Autowired
private UserDaoImpl userDaoImpl;
...
#RemoteMethod
public void sendMail(String EmailId) {
System.out.println("DWR Called.");
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
...
}
...
}

Spring Security cannot reach custom userDetailsService Bean in Service layer

Edit: I just realized that the issue does not come from spring-security not being able to instantiate userDetailsServiceImpl that is referenced in the spring-security.xml file, it is the addUserFormController that cannot be instantiated because it cannot autowire the UserDetailsServiceImpl. So the problem comes from the fact that this Controller cannot reach, for whatever reasons, this Service bean UserDetailsServiceImpl. I think I did properly made my component scan, by only scanning the controllers in mvc-dispatcher-servlet.xml, and all the other one except controller in the applicationContext.
I am using Spring MVC and Hibernate and I am trying to integrate Spring Security with a custom UserDetailsService and an Assembler.
It looks like my spring security cannot access the beans that are supposed to be scanned by the applicationContext.xml.
When loading my application I am running into the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addUserFormController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.controller.AddUserFormController.setUserDetailsService(com.service.UserDetailsServiceImpl); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.service.UserDetailsServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
Here is my spring-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<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>
Here is my 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>
<!-- This listener creates the root application Context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.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>
Here is my 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-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>
<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="packagesToScan">
<list>
<value>com.service</value>
<value>com.dao</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/tutospringsource" />
<property name="username" value="root" />
<property name="password" value="password" />
</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>
<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>
And finally, my 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>
</beans>
My AddUserFormController:
#Controller
#RequestMapping("/register.htm")
public class AddUserFormController {
private UserDetailsServiceImpl userDetailsService;
#Autowired
public void setUserDetailsService(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
My UserDetailsServiceImpl:
package com.service;
#Service("userDetailsService")
#Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserEntityDAO dao;
#Autowired
private Assembler assembler;
I have been able to fix that issue.
In my AddUserFormController, I had this:
#Controller
#RequestMapping("/register.htm")
public class AddUserFormController {
private UserDetailsService userDetailsService;
#Autowired
public void setUserDetailsService(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
Here is how it looks now:
#Controller
#RequestMapping("/register.htm")
public class AddUserFormController {
#Autowired
private UserDetailsService userDetailsService;
public void setUserDetailsService(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
I moved the #Autowired from the setter directly to the attribute, AND most important, I changed the type of userDetailsService to UserDetailsService, rather than UserDetailsServiceImpl.

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