#ManagedProperty in a Spring managed bean is null - spring

I've some trouble with injecting one managedbean in another by defining a managedproperty. I'm googling and stackoverflowing now for 3 days, but with no result...
I'm developing with eclipse 4.2 and deploying to an integrated Tomcat 7
So, can anybody tell me, why my property is null?
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.0.5.RELEASE</spring.version>
<java.version>1.6</java.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
web.xml
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
I have set the beans in applicationContext for scanning #Autowired annotation. (Yes, i tried it without beans in applicationContext, but ManagedProperty will not be set, too.)
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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="myPackage" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="myPackage.dao.UserDao" id="userDao" />
<bean class="myPackage.dao.WorldDao" id="worldDao" />
<bean class="myPackage.dao.BuildingTypeDao" id="buildingTypeDao" />
<bean class="myPackage.dao.BuffTypeDao" id="buffTypeDao" />
<bean class="myPackage.dao.ClanDao" id="clanDao" />
<bean class="myPackage.bean.MainBean" id="mainBean" />
<bean class="myPackage.bean.UserBean" id="userBean" />
<bean class="myPackage.bean.AdminBean" id="adminBean" />
MainBean
package myPackage.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import myPackage.model.MainModel;
#ManagedBean
#SessionScoped
public class MainBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(MainBean.class);
private MainModel model;
/**
* #return the model
*/
public MainModel getModel() {
if (model == null) {
model = new MainModel();
}
return model;
}
/**
* #param model the model to set
*/
public void setModel(MainModel model) {
this.model = model;
}
}
UserBean
package myPackage.bean;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import myPackage.dao.UserDao;
import myPackage.entity.User;
#ManagedBean
#RequestScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(UserBean.class);
#ManagedProperty(value="#{mainBean}")
private MainBean mainBean;
#Autowired
private UserDao userDao;
/**
* #return the mainBean
*/
public MainBean getMainBean() {
return mainBean;
}
/**
* #param mainBean the mainBean to set
*/
public void setMainBean(MainBean mainBean) {
this.mainBean = mainBean;
}
public String doLogin() {
User user = userDao.getUserByUsernameAndPassword(getMainBean().getModel().getUser().getUsername(), getMainBean().getModel().getUser().getPassword());
if (user != null) {
getMainBean().getModel().setUser(user);
logger.info("User '"+getMainBean().getModel().getUser().getUsername()+"' logged in");
getMainBean().getModel().setSelectedTab(0);
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login failed", "Username and/or password wrong!"));
logger.warn("User '"+getMainBean().getModel().getUser().getUsername()+"' login failed");
}
return null;
}
UserDao
package myPackage.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import myPackage.entity.User;
#Repository
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void save(User user) {
if (user.getId() == null) {
entityManager.persist(user);
} else {
entityManager.merge(user);
}
}
#SuppressWarnings("unchecked")
public List<User> list() {
return entityManager.createQuery("select u from User u")
.getResultList();
}
public User getUserByUsername(String username) {
try {
Query q = entityManager.createQuery("select u from User u where u.username = :username");
q.setParameter("username", username);
User u = (User) q.getSingleResult();
return u;
} catch (Exception e) {
return null;
}
}
public User getUserByUsernameAndPassword(String username, String password) {
try {
Query q = entityManager.createQuery("select u from User u where u.username = :username and u.password = :password");
q.setParameter("username", username);
q.setParameter("password", password);
User u = (User) q.getSingleResult();
return u;
} catch (Exception e) {
return null;
}
}
#Transactional
public User getUserById(Long id) {
return entityManager.find(User.class, id);
}
#Transactional
public void delete(User user) {
entityManager.remove(user);
}
public void deleteById(Long id) {
delete(getUserById(id));
}
}
And now the Exception...
Caused by: java.lang.NullPointerException
at myPackage.bean.UserBean.doLogin(UserBean.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Line 47:
User user = userDao.getUserByUsernameAndPassword(getMainBean().getModel().getUser().getUsername(), getMainBean().getModel().getUser().getPassword());
Debugging shows that getMainBean() returns null.
I'm open for suggests to improve my concept!

Your JSF backing beans (MainBean and UserBean) should be managed either by JSF or by Spring, but not by both of them.
If your beans are managed by JSF:
You annotate them with #ManagedBean and #...Scoped
You don't need to declare them in applicationContext.xml
You use #ManagedProperty instead of #Autowired, even if you need to inject beans managed by Spring (don't forget setters, #ManagedProperty requires it):
#ManagedProperty("#{userDao}")
private UserDao userDao;
If your beans are managed by Spring:
You declare them in applicationContext.xml with appropriate scopes (view scope is not supported)
You don't need #ManagedBean and #...Scoped
You use #Autowired instead of #ManagedProperty and you cannot inject beans managed by JSF this way
In both cases you need to configure Spring-JSF bridge in faces-context.xml:
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>

Related

NullPointerException while using #Autowired in maven webapp

I am trying to integrate Jersey with Spring using maven webapp-archetype. When I get the object form the ApplicationContext I see my code executing, but when I try to use #Autowired it throws me NullPointerException. Following are the code snippets:
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pack.resource" />
<bean id="person" class="com.pack.resource.Person">
<property name="name" value="SomeNamexxxx" />
</bean>
Person.java
package com.pack.resource;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
}
Hello.java
package com.pack.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
#Component
#Path("/hello")
public class Hello {
#Autowired
Person person;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getName() {
return person.getName();
}
}
But when I use ApplicationContext.getBean("person").getName() it gives me the actual value inside the bean property.
Why is #Autowired annotation not working as it should. Kindly help me.
TIA!

Spring service injection with #Autowired results NullPointerException

I am trying to inject a service in GeofenceMonitoring class using
#Autowired
private IDeviceService deviceService;
but I am getting a NullPointerException
This is the interface of the service and below it's implementation :
IDeviceService
package com.sifast.gpstracking.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.service.util.IGenericService;
#Transactional
public interface IDeviceService extends IGenericService<Device, Integer> {
Device findDeviceByUniqueId(String uniqueId);
List<Device> findAllDevice();
}
DeviceService
package com.sifast.gpstracking.service.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sifast.gpstracking.dao.impl.DeviceDao;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.service.IDeviceService;
import com.sifast.gpstracking.service.util.GenericService;
#Service("deviceService")
public class DeviceService extends GenericService<Device, Integer> implements IDeviceService, Serializable {
private static final long serialVersionUID = 1L;
#Autowired
private DeviceDao deviceDao;
#Override
public Device findDeviceByUniqueId(String uniqueId) {
Query query = deviceDao.getSession().getNamedQuery("findDeviceByUniqueId").setString("uniqueId", uniqueId);
return deviceDao.findOne(query);
}
#Override
public List<Device> findAllDevice() {
return deviceDao.findAll(Device.class);
}
}
And here when I try to inject the service :
GeofenceMonitoring
package com.sifast.gpstracking.webServiceRest;
import java.util.ArrayList;
import java.util.List;
import org.primefaces.model.map.LatLng;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import com.sifast.gpastracking.monitoring.IMonitor;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.model.Geofence;
import com.sifast.gpstracking.model.GeofenceDevice;
import com.sifast.gpstracking.model.Point;
import com.sifast.gpstracking.push.DevicePositionData;
import com.sifast.gpstracking.service.IDeviceService;
import com.sifast.gpstracking.service.util.IntersectionGeofence;
#ComponentScan("com.sifast.gpstracking")
public class GeofenceMonitor implements IMonitor {
ArrayList<Geofence> geofences = new ArrayList<Geofence>();
GeofenceDevice geofenceDevice;
Boolean geofenced=false;
public static final Logger logger = LoggerFactory.getLogger(GeofenceMonitor.class);
#Autowired
private IDeviceService serviceDevice;
public GeofenceMonitor() {
}
#Override
public void updateMonitor(DevicePositionData devicePositionData) {
//logger.debug("DEVICE ID = " + devicePositionData.getUniqueId());
Device device = serviceDevice.findDeviceByUniqueId(devicePositionData.getUniqueId());
LatLng currentPosition = new LatLng(devicePositionData.getLatitude(), devicePositionData.getLongitude());
for (GeofenceDevice geofenceDevice : device.getListGeofenceDevice()) {
List<LatLng> listPoint = convertListPointToListLatLng(geofenceDevice.getGeofence().getListPoint());
logger.debug("SIZE =====> "+listPoint.size());
if (IntersectionGeofence.isPointInsidePolygon(currentPosition, listPoint))
{
geofenced = true;
logger.debug("Le device " + devicePositionData.getDeviceName() + " a dépassé la zone limitée");
break;
}
}
}
private List<LatLng> convertListPointToListLatLng(List<Point> listPoint)
{
List<LatLng> listLatLng = new ArrayList<LatLng>();
for (Point point : listPoint){
listLatLng.add(new LatLng(point.getLatitude(),point.getLongitude()));
}
return listLatLng;
}
}
And finally 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:aop="http://www.springframework.org/schema/aop"
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-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<!-- Activates scanning of annotations -->
<context:component-scan base-package="com.sifast.gpstracking" />
<context:annotation-config/>
<context:spring-configured/>
<!-- Database Configuration -->
<import resource="/database/dataSource.xml" />
<import resource="/database/hibernate.xml" />
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager" />
<mvc:annotation-driven></mvc:annotation-driven>
<!-- Pour avoir accès au resources comme les fichiers /js et /css lorsqu'on utilise un mapping / avec le servletDispatcher dans le web.xml -->
<mvc:resources mapping="/css/**" location="/resources/css/" />
<mvc:resources mapping="/images/**" location="/resources/images/" />
<!-- Init DataBase -->
<bean id="dbInit"
class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts">
<list>
<value>classpath:sql/1.0.0/CreateData.sql</value>
</list>
</property>
<property name="continueOnError" value="true" />
</bean>
<bean id="startupScripts"
class="org.springframework.jdbc.datasource.init.DataSourceInitializer">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="databasePopulator">
<ref bean="dbInit" />
</property>
</bean>
</beans>
It's because that IDeviceService is an interface. Spring won't know which instance you want to autowire, since the default way to autowire is byType, if I'm not wrong.
Try this
#Autowired
#Qualifier("deviceService")
private IDeviceService deviceService;
try double stars first
<context:component-scan base-package="com.sifast.gpstracking.**" />
An simple example to get bean via applicationContext.getBean()
http://www.mkyong.com/spring/quick-start-maven-spring-example/
And you want to get it in web environment, you can inject it.
How to inject ApplicationContext itself
Is your GeofenceMonitor bean registered in the application context ? From your code snippets its missing streotype annotations (#Component / #Service etc) So it wont be auto detected and any specified dependencies wont be injected. Change #ComponentScan("com.sifast.gpstracking")
public class GeofenceMonitor implements IMonitor to #Component public class GeofenceMonitor implements IMonitor
the problem was that I am creating a new instance of GeofenceMonitor with new GeofenceMonitor() in a service class that's meant to handle the web service invokation.
So I modified it to #Scope("singleton") and added #PostConstruct private void init(). Below is my code:
PositionNotification (web service class)
#Service("positionNotification")
#Path("/positionNotification")
#Scope("singleton")
public class PositionNotification implements Serializable, IMonitorable {
private static final long serialVersionUID = 1L;
#Autowired
private GeofenceMonitor geofence;
private static ArrayList<IMonitor> monitors;
/*static {
monitors = new ArrayList<IMonitor>();
monitors.add(new SpeedMonitor());
monitors.add(geofence);
}*/
#Autowired
private IDeviceService deviceService;
#Autowired
private IPositionService positionService;
private final static String CHANNEL = "/notify";
public static final Logger logger = LoggerFactory.getLogger(PositionNotification.class);
private static final int STATUS_OK = 200;
#PostConstruct
private void init(){
monitors = new ArrayList<IMonitor>();
monitors.add(new SpeedMonitor());
monitors.add(geofence);
}
#POST
#Path("/getGeoLocFromDevice")
public Response test(#FormParam("LATITUDE") String latitude, #FormParam("LONGITUDE") String longitude, #FormParam("DEVICE_ID") String uniqueId,
#FormParam("SPEED") String speed, #FormParam("Horodateur") String date) {
logger.debug("X long: " + latitude + " __ Y lat: " + longitude + " uniqueId " + uniqueId + " " + date);
Device device = deviceService.findDeviceByUniqueId(uniqueId);
if (device != null) {
if (speed == null) {
speed = "0";
}
String address = AddressResolver.AddressReseolve(latitude, longitude);
DevicePositionData devicePositionData = new DevicePositionData();
devicePositionData.setLatitude(Double.valueOf(latitude));
devicePositionData.setLongitude(Double.valueOf(longitude));
devicePositionData.setUniqueId(uniqueId);
devicePositionData.setAddress(address);
devicePositionData.setDeviceName(device.getName());
devicePositionData.setSpeed(Double.parseDouble(speed));
devicePositionData.setIcon(device.getType().getIconActive());
Position position = new Position();
position.setAddress(address);
position.setLatitude(Double.valueOf(latitude));
position.setLongitude(Double.valueOf(longitude));
if (date != null) {
try {
position.setDatePosition(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(date));
devicePositionData.setDatePosition(date);
device.setLastUpdate(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
position.setDatePosition(new Date());
devicePositionData.setDatePosition(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()));
device.setLastUpdate(new Date());
}
position.setSpeed(Double.parseDouble(speed));
position.setDevice(device);
positionService.saveOrUpdateService(position);
deviceService.saveOrUpdateService(device);
if (EventBusFactory.getDefault() != null) {
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish(CHANNEL, devicePositionData);
}
notifyMonitors(devicePositionData);
}
return Response.status(STATUS_OK).build();
}
#Override
public void notifyMonitors(DevicePositionData devicePositionData) {
for (IMonitor monitor : monitors) {
monitor.updateMonitor(devicePositionData);
}
}
#Override
public void addMonitor(IMonitor monitor) {
monitors.add(monitor);
}
#Override
public void deleteMonitor(IMonitor monitor) {
monitors.remove(monitor);
}
#Override
public void clearMonitors() {
monitors.clear();
}
}

#Autowired not working when using spring-security (neo4j as database)

I forked an example-spring-data-neo4j project, and build my own 'StigMod' project from it.
Everything works fine, until I tried to change the controller-service-repository structure of this project.
My Controller -> Service -> Repository structure.
#Controller
public class StigModController {
...
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
...
}
#Service
public class StigmodUserDetailsService implements UserDetailsService {
...
#Autowired
private UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
Structure in the example:
#Controller
public class AuthController {
...
#Autowired
UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User>, CineastsUserDetailsService {
User findByLogin(String login);
}
#Service
public class CineastsUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
}
public class UserRepositoryImpl implements CineastsUserDetailsService {
#Autowired
private UserRepository userRepository;
}
After my refactoring, a problem popped out:
The StigmodUserDetailsService class is annotated with #Service. Component scan is enabled in package net.stigmod, and my IDE actually could recognize all the #Autowire dependencies in all files.
However, the autowired field stigmodUserDetailsService in StigModController.java could not be initialized during deployment.
I tried several methods proposed by people in some similar questions, but they did not work. I guess there is soming wrong with the spring-security dymamic object feature, but I am not sure.
I posted most of the related complete codes below. Hope someone could help me out. Thank you so much!
### ERROR in Tomcat Localhost Log during deployment ###
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stigModController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 56 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 58 more
### 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>Spring MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<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>
<servlet>
<servlet-name>StigMod</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StigMod</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
### applicationContext.xml ###
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<tx:annotation-driven mode="proxy"/>
</beans>
### applicationContext-security.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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<security:global-method-security secured-annotations="enabled">
</security:global-method-security>
<security:http> <!-- use-expressions="true" -->
<security:intercept-url pattern="/" access="isAnonymous()"/>
<security:intercept-url pattern="/static/**" access="permitAll"/>
<security:intercept-url pattern="/about" access="permitAll"/>
<security:intercept-url pattern="/signin*" access="isAnonymous()"/>
<security:intercept-url pattern="/signup*" access="isAnonymous()"/>
<security:intercept-url pattern="/**" access="isFullyAuthenticated()"/>
<security:form-login login-page="/signin"
authentication-failure-url="/signin?login_error=true"
default-target-url="/user"
login-processing-url="/signin"
username-parameter="mail"
password-parameter="password"/>
<security:access-denied-handler error-page="/denied" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="stigmodUserDetailsService">
<security:password-encoder hash="md5">
<security:salt-source system-wide="xxxxxx"/>
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
</beans>
### StigMod-servelet.xml ###
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="net.stigmod.controller"/>
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<mvc:annotation-driven/>
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="configLocation" value="/WEB-INF/velocity.properties"/>
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
</beans>
### Application.java ###
package net.stigmod;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import net.stigmod.util.config.Neo4j;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.server.RemoteServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableNeo4jRepositories("net.stigmod.repository")
#EnableTransactionManagement
#ComponentScan("net.stigmod")
public class Application extends Neo4jConfiguration {
// Common settings
private Config config = ConfigLoader.load();
private Neo4j neo4j = config.getNeo4j();
private String host = neo4j.getHost();
private String port = neo4j.getPort();
private String username = neo4j.getUsername();
private String password = neo4j.getPassword();
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("net.stigmod.domain");
}
#Override
#Bean
public Neo4jServer neo4jServer() {
return new RemoteServer("http://" + host + ":" + port, username, password);
}
#Override
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
### StigModController.java ###
package net.stigmod.controller;
import net.stigmod.domain.node.User;
import net.stigmod.service.StigmodUserDetailsService;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#Controller
public class StigModController {
// Common settings
private Config config = ConfigLoader.load();
private String host = config.getHost();
private String port = config.getPort();
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
// front page
#RequestMapping(value="/", method = RequestMethod.GET)
public String index(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "index");
return "index";
}
// about this web app
#RequestMapping(value="/about", method = RequestMethod.GET)
public String about(ModelMap model) {
final User user = stigmodUserDetailsService.getUserFromSession();
model.addAttribute("user", user);
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "about");
return "about";
}
// sign up page GET
#RequestMapping(value="/signup", method = RequestMethod.GET)
public String reg(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signup";
}
// sign up page POST
#RequestMapping(value="/signup", method = RequestMethod.POST)
public String regPost(
#RequestParam(value = "mail") String mail,
#RequestParam(value = "password") String password,
#RequestParam(value = "password-repeat") String passwordRepeat,
ModelMap model, HttpServletRequest request) {
try {
stigmodUserDetailsService.register(mail, password, passwordRepeat);
return "redirect:/user";
} catch(Exception e) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
model.addAttribute("mail", mail);
model.addAttribute("error", e.getMessage());
return "signup";
}
}
// sign in page GET (POST route is taken care of by Spring-Security)
#RequestMapping(value="/signin", method = RequestMethod.GET)
public String login(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign In");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signin";
}
// sign out
#RequestMapping(value="/signout", method = RequestMethod.GET)
public String logout (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/signin";
}
// Denied page GET
#RequestMapping(value="/denied", method = RequestMethod.GET)
public String reg(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Denied");
return "denied";
}
}
### UserRepository.java ###
package net.stigmod.repository.node;
import net.stigmod.domain.node.User;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
### StigmodUserDetails.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class StigmodUserDetails implements UserDetails {
private final User user;
public StigmodUserDetails(User user) {
this.user = user;
}
#Override
public Collection<GrantedAuthority> getAuthorities() {
User.SecurityRole[] roles = user.getRole();
if (roles == null) {
return Collections.emptyList();
}
return Arrays.<GrantedAuthority>asList(roles);
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getMail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public User getUser() {
return user;
}
}
### StigmodUserDetailsService.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import net.stigmod.repository.node.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class StigmodUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
public StigmodUserDetailsService() {}
public StigmodUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public StigmodUserDetails loadUserByUsername(String mail) throws UsernameNotFoundException {
final User user = userRepository.findByMail(mail);
if (user == null) {
throw new UsernameNotFoundException("Username not found: " + mail);
}
return new StigmodUserDetails(user);
}
public User getUserFromSession() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof StigmodUserDetails) {
StigmodUserDetails userDetails = (StigmodUserDetails) principal;
return userDetails.getUser();
}
return null;
}
#Transactional
public User register(String mail, String password, String passwordRepeat) {
User found = userRepository.findByMail(mail);
if (found != null) {
throw new RuntimeException("Email already taken: " + mail);
}
if (password == null || password.isEmpty()) {
throw new RuntimeException("No password provided.");
}
if (passwordRepeat == null || passwordRepeat.isEmpty()) {
throw new RuntimeException("No password-repeat provided.");
}
if (!password.equals(passwordRepeat)) {
throw new RuntimeException("Passwords provided do not equal.");
}
User user = userRepository.save(new User(mail, password, User.SecurityRole.ROLE_USER));
setUserInSession(user);
return user;
}
void setUserInSession(User user) {
SecurityContext context = SecurityContextHolder.getContext();
StigmodUserDetails userDetails = new StigmodUserDetails(user);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities());
context.setAuthentication(authentication);
}
}

java.lang.NullPointerException on #Inject Dao

I'm trying to Inject a DAO into #Service component, but I get this error :
Exception in thread "main" java.lang.NullPointerException at
it.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24).
Fails to call the DAO which is null despite the annotation #Autowired
Below my code:
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- INIZIO IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<tx:annotation-driven/>
<context:property-placeholder location="classpath:hibernate.properties"/>
<context:component-scan base-package="it.cle.project.service.impl" />
<context:component-scan base-package="it.cle.project.dao.hbn" />
<context:component-scan base-package="it.cle.project.dao.hibernate" />
<!-- FINE IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<!-- INIZIO IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hibernate.properties"/>
</bean>
<!-- FINE IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<!-- INIZIO IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</prop>
</util:properties>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean "
p:dataSource-ref="dataSource" p:packagesToScan="it.cle.project.model"
p:hibernateProperties-ref="hibernateProperties" />
<!-- FINE IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
App.java
package it.cle.project;
import it.cle.project.model.TestEntity;
import it.cle.project.service.impl.TestEntityServiceImpl;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
System.out.println( "Hello World!" );
TestEntity testEntity = new TestEntity();
testEntity.setCampoUno("Campo Uno");
testEntity.setCampoDue("Campo Due");
testEntity.setEmail("email#test.it");
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
List<TestEntity> testEntitys = testEntityServiceImpl.getListTestEntity();
}
}
DAO Interface
package it.cle.project.dao;
import java.io.Serializable;
import java.util.List;
public interface Dao<T extends Object> {
void create(T t);
T get(Serializable id);
T load(Serializable id);
List<T> getAll();
void update(T t);
void delete(T t);
void deleteById(Serializable id);
void deleteAll();
long count();
boolean exists(Serializable id);
}
TestEntityDAO interface
package it.cle.project.dao;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityDao extends Dao<TestEntity> {
List<TestEntity> findByEmail(String email);
}
AbstractHbnDao Abstract class:
package it.cle.project.dao.hibernate;
import it.cle.project.dao.Dao;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
#Service
public abstract class AbstractHbnDao<T extends Object> implements Dao<T> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> domainClass;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
if (domainClass == null) {
ParameterizedType thisType =
(ParameterizedType) getClass().getGenericSuperclass();
this.domainClass =
(Class<T>) thisType.getActualTypeArguments()[0];
}
return domainClass;
}
private String getDomainClassName() {
return getDomainClass().getName();
}
public void create(T t) {
Method method = ReflectionUtils.findMethod(
getDomainClass(), "setDataCreazione",
new Class[] { Date.class });
if (method != null) {
try {
method.invoke(t, new Date());
} catch (Exception e) { /* Ignore */ }
}
getSession().save(t);
}
#SuppressWarnings("unchecked")
public T get(Serializable id) {
return (T) getSession().get(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public T load(Serializable id) {
return (T) getSession().load(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return getSession()
.createQuery("from " + getDomainClassName())
.list();
}
public void update(T t) { getSession().update(t); }
public void delete(T t) { getSession().delete(t); }
public void deleteById(Serializable id) { delete(load(id)); }
public void deleteAll() {
getSession()
.createQuery("delete " + getDomainClassName())
.executeUpdate();
}
public long count() {
return (Long) getSession()
.createQuery("select count(*) from " + getDomainClassName())
.uniqueResult();
}
public boolean exists(Serializable id) { return (get(id) != null); }
}
HbnTestEntityDao class DAO
package it.cle.project.dao.hbn;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.dao.hibernate.AbstractHbnDao;
import it.cle.project.model.TestEntity;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class HbnTestEntityDao extends AbstractHbnDao<TestEntity> implements TestEntityDao {
#SuppressWarnings("unchecked")
public List<TestEntity> findByEmail(String email) {
return getSession()
.getNamedQuery("findContactsByEmail")
.setString("email", "%" + email + "%")
.list();
}
}
TestEntityService interface service
package it.cle.project.service;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityService {
void createTestEntity(TestEntity testEntity);
List<TestEntity> getListTestEntity();
List<TestEntity> getTestEntityByEmail(String email);
TestEntity getTestEntity(Integer id);
void updateTestEntity(TestEntity testEntity);
void deleteTestEntity(Integer id);
}
TestEntityServiceImpl
package it.cle.project.service.impl;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.model.TestEntity;
import it.cle.project.service.TestEntityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class TestEntityServiceImpl implements TestEntityService {
#Autowired
private TestEntityDao testEntityDao;
public void createTestEntity(TestEntity testEntity) {
testEntityDao.create(testEntity);
}
public List<TestEntity> getListTestEntity() {
return testEntityDao.getAll();
}
public List<TestEntity> getTestEntityByEmail(String email) {
return testEntityDao.findByEmail(email);
}
public TestEntity getTestEntity(Integer id) {
return testEntityDao.get(id);
}
public void updateTestEntity(TestEntity testEntity) {
testEntityDao.update(testEntity);
}
public void deleteTestEntity(Integer id) {
testEntityDao.deleteById(id);
}
}
Any ideas?
Thanks.
Your TestServiceImpl should be spring managed bean and should be fetched from Spring application context (by injection or by explicit asking the context). As the component scanning is at work, your TestServiceImpl is already managed with Spring's own supplied name (com...TestServiceImpl becomes testServiceImpl). You can give it your name like
#Service("myTestServiceImpl")
The instead of creating the bean yourself you can query this named bean from application context and use it.
That's some wall of text. I stopped at:
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
You created an unmanaged bean. Spring has no control over that. Put TestEntityServiceImpl into your spring context.

#Autowired field get null

I have this property-editor for my class Categoria and im trying to auto-wired it to the service, the problem its that the services keep getting a null value.
Also it seems like this is isolated or at least thats what i think, because i auto-wired a field of the same class at a controller, so i don't know whats going on, i already got an error like this, but at that time it didn't work at all .
Convertor
package com.carloscortina.paidosSimple.converter;
import java.beans.PropertyEditorSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.service.CategoriaService;
public class CategoriaConverter extends PropertyEditorSupport{
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private CategoriaService categoriaService;
#Override
public void setAsText(String categoria) {
logger.info(categoria);
Categoria cat = new Categoria();
cat = categoriaService.getCategoria(Integer.parseInt(categoria));
setValue(cat);
}
}
Service
package com.carloscortina.paidosSimple.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.carloscortina.paidosSimple.dao.CategoriaDao;
import com.carloscortina.paidosSimple.model.Categoria;
#Service
#Transactional
public class CategoriaServiceImpl implements CategoriaService{
#Autowired
private CategoriaDao categoriaDao;
#Override
public Categoria getCategoria(int id) {
// TODO Auto-generated method stub
return categoriaDao.getCategoria(id);
}
#Override
public List<Categoria> getCategorias() {
return categoriaDao.getCategorias();
}
}
Here It does Work
Controller
package com.carloscortina.paidosSimple.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;
#Controller
public class PersonalController {
private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);
#Autowired
private PersonalService personalService;
#Autowired
private UsuarioService usuarioService;
#Autowired
private CategoriaService categoriaService;
#RequestMapping(value="/usuario/add")
public ModelAndView addUsuarioPage(){
ModelAndView modelAndView = new ModelAndView("add-usuario-form");
modelAndView.addObject("categorias",categorias());
modelAndView.addObject("user", new Usuario());
return modelAndView;
}
#RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
public ModelAndView addingUsuario(#ModelAttribute Usuario user){
ModelAndView modelAndView = new ModelAndView("add-personal-form");
usuarioService.addUsuario(user);
logger.info(modelAndView.toString());
String message= "Usuario Agregado Correctamente.";
modelAndView.addObject("message",message);
modelAndView.addObject("staff",new Personal());
return modelAndView;
}
#RequestMapping(value="/personal/list")
public ModelAndView listOfPersonal(){
ModelAndView modelAndView = new ModelAndView("list-of-personal");
List<Personal> staffMembers = personalService.getAllPersonal();
logger.info(staffMembers.get(0).getpNombre());
modelAndView.addObject("staffMembers",staffMembers);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
public ModelAndView editPersonalPage(#PathVariable int id){
ModelAndView modelAndView = new ModelAndView("edit-personal-form");
Personal staff = personalService.getPersonal(id);
logger.info(staff.getpNombre());
modelAndView.addObject("staff",staff);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingPersonal(#ModelAttribute Personal staff, #PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.updatePersonal(staff);
String message = "Personal was successfully edited.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
public ModelAndView deletePersonal(#PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.deletePersonal(id);
String message = "Personal was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
private Map<String,String> categorias(){
List<Categoria> lista = categoriaService.getCategorias();
Map<String,String> categorias = new HashMap<String, String>();
for (Categoria categoria : lista) {
categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
}
return categorias;
}
#InitBinder
public void initBinderAll(WebDataBinder binder){
binder.registerCustomEditor(Categoria.class, new CategoriaConverter());
}
}
DAO
package com.carloscortina.paidosSimple.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
#Repository
public class CategoriaDaoImp implements CategoriaDao {
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public Categoria getCategoria(int id) {
Categoria rol = (Categoria) getCurrentSession().get(Categoria.class, id);
if(rol == null) {
logger.debug("Null");
}else{
logger.debug("Not Null");
}
logger.info(rol.toString());
return rol;
}
#Override
#SuppressWarnings("unchecked")
public List<Categoria> getCategorias() {
// TODO Auto-generated method stub
return getCurrentSession().createQuery("from Categoria").list();
}
}
root-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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Enable transaction Manager -->
<tx:annotation-driven/>
<!-- DataSource JNDI -->
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" />
<!-- Session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:hibernateProperties-ref="hibernateProperties"
p:packagesToScan="com.carloscortina.paidosSimple.model" />
<!-- Hibernate Properties -->
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<context:annotation-config />
<context:component-scan base-package="com.carloscortina.paidosSimple,com.carlosocortina.paidosSimple.converter,com.carlosocortina.paidosSimple.service,com.carlosocortina.paidosSimple.dao" />
</beans>
Thanks in advance
Your are creating your PropertyEditor outside spring context using new operator (binder.registerCustomEditor(Categoria.class, new CategoriaConverter());) so service is not injected: follow the guide at this link to solve your problem.

Resources