why is autowired null? use spring jersey integration - spring

I have a application controller with a method getApplication(). This method returns a applicationJson objekt for my client.
In this method i call on an application builder.
The application builder is a factory and generate a special application builder object.
In the special application builders be used mapper and services, the services used daos.
All services and daos sind beans and confirgure in the applicationContext.xml and serviceBeans.xml.
When calling the method getApplication() is an exception in my eclipse java console.
The problem occurs in the class MobileApplicationBuilder and method buildPagenaviData()
Class ApplicationController:
package core.application.controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import core.application.builder.ApplicationBuilder;
import core.application.builder.MobileApplicationBuilder;
import core.application.factories.ApplicationControllerProcessHelperFactory;
import core.application.mapper.json.ApplicationJson;
import core.application.process.helper.MobileApplicationBuildHelper;
import core.base.abstracts.ControllerAbstract;
import core.security.model.interfaces.SystemSettingsModelInterface;
import core.security.service.interfaces.SystemLanguagesServiceInterface;
import core.security.service.interfaces.SystemSettingsServiceInterface;
import core.security.service.interfaces.SystemUserServiceInterface;
/**
*
* Class: {#link ApplicationController}
*
* Über diesen Controller wird die Anwendung zusammengebaut und als großes JSON Objekt an den Client geschickt.
*
*/
#Path("/app")
#Component
#Scope("session")
public class ApplicationController extends ControllerAbstract {
private static final String JSON_PATH = System.getProperty("wtp.deploy") + "/decon_fm_version5/WEB-INF/classes/json/";
#Autowired
private ApplicationBuilder applicationBuilder;
#Autowired
#Qualifier("systemUserService")
private SystemUserServiceInterface systemUserService;
#Autowired
#Qualifier("systemLanguagesService")
private SystemLanguagesServiceInterface languagesService;
#Autowired
#Qualifier("systemSettingsService")
private SystemSettingsServiceInterface systemSettings;
private ApplicationJson applicationJson = null;
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
/**
* Process für den Build der gesamten Applikation.
* Es wird ein gemapptes JSON Objekt zurück gegeben welches dann auf dem Client verarbeitet werden kann.
* Größere Build Logiken werden in eine Helper Klasse ausgelagert, welche über eine entsprechende Factory geladen wird.
* #return
*/
#GET
#Path("/build")
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ApplicationJson getApplication() {
// auslesen und Zuwiesung der User Settings
SystemSettingsModelInterface settingsModel = systemSettings.getSettingsByUser(Long.parseLong(session.getAttribute("idUser").toString()));
systemUserService.model().setSettings(settingsModel);
applicationBuilder.setClientApp(settingsModel.getClientView())
.setSession(session)
.setUserModel(this.deconSecurity.getUser());
applicationJson = applicationBuilder.build();
return applicationJson;
}
}
Class ApplicationBuilder:
package core.application.builder;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import core.application.mapper.json.ApplicationJson;
import core.security.model.interfaces.SystemUserModelInterface;
import core.security.service.interfaces.SystemLanguagesServiceInterface;
public class ApplicationBuilder {
/**
* Klassennamen Suffix für jeden Builder
*/
private static final String CLASS_SUFFIX = "ApplicationBuilder";
/**
* http session objekt aus dem controller
*/
private HttpSession session;
/**
* Client Application die vom Nutzer eingestellt wurde
*/
private String clientApp;
private SystemUserModelInterface userModel;
#Autowired
#Qualifier("systemLanguagesService")
private SystemLanguagesServiceInterface languageService;
/**
* Auszuführender Builder gegen Interface Sicherung
*/
private ApplicationBuilderInterface builder;
public ApplicationJson build() {
ApplicationJson application = null;
try {
builder = (ApplicationBuilderInterface) Class.forName("core.application.builder." + WordUtils.capitalize(clientApp) + CLASS_SUFFIX).newInstance();
builder.setSession(session);
builder.setUserModel(userModel);
builder.setLanguages(languageService.getLanguages());
builder.setFavorite(userModel.getSettings().getFavorite());
application = builder.build();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return application;
}
public ApplicationBuilder setClientApp(String clientApp) {
this.clientApp = clientApp;
return this;
}
public ApplicationBuilder setSession(HttpSession session) {
this.session = session;
return this;
}
public ApplicationBuilder setUserModel(SystemUserModelInterface userModel) {
this.userModel = userModel;
return this;
}
}
Class MobileApplicationBuilder:
package core.application.builder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import core.application.mapper.json.ApplicationAnimateDataJson;
import core.application.mapper.json.ApplicationIconbarJson;
import core.application.mapper.json.ApplicationJson;
import core.application.mapper.json.ApplicationPagenaviJson;
import core.application.mapper.json.Formular;
import core.application.mapper.json.MobileApplicationJson;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
import core.cache.service.ApplicationCacheService;
#Component
#Scope("session")
public class MobileApplicationBuilder extends ApplicationBuilderAbstract implements ApplicationBuilderInterface {
private static final String JSON_PATH = System.getProperty("wtp.deploy") + "/decon_fm_version5/WEB-INF/classes/json/";
private MobileApplicationJson mapper = new MobileApplicationJson();
#Autowired
#Qualifier("applicationCacheService")
private ApplicationCacheService applicationCacheService;
public ApplicationJson build() {
mapper.setStartPage(getFavorite())
.setSystemLangguages(getLanguages())
.setSystemUser(getUserModel());
buildIconbar();
buildAnimateData();
buildPagenaviData();
return mapper;
}
/**
* Zusammenbau sämtlicher Iconbars im System
*/
protected void buildIconbar() {
ApplicationIconbarJson iconbarMapper = new ApplicationIconbarJson();
File directory = new File(JSON_PATH + "/iconbars/");
File[] files = directory.listFiles();
Formular formsMapper = new Formular();
for (int i = 0; i < files.length; i++) {
try {
byte[] iconbar = Files.readAllBytes(Paths.get(files[i].getAbsolutePath()));
iconbarMapper = getObjectMapper().readValue(iconbar, ApplicationIconbarJson.class);
mapper.setIconbars(iconbarMapper.getName().toString(), iconbarMapper);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Zusammenbau der Animate Pages für die Application
*/
protected void buildAnimateData() {
ApplicationAnimateDataJson aadnMapper = new ApplicationAnimateDataJson();
try {
byte[] animateData = Files.readAllBytes(Paths.get(JSON_PATH + "anmiate_data.json"));
aadnMapper = getObjectMapper().readValue(animateData, ApplicationAnimateDataJson.class);
mapper.setAnimateData(aadnMapper);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Zusammenbau des Objektes für Daten der Module welche in der Applikation verfügbar sein sollen
*/
protected void buildPagenaviData() {
String component = "pagenaviData";
// ApplicationCacheServiceInterface cacheService = new ApplicationCacheService();
// here arises a problem
ApplicationCacheModelInterface cache = applicationCacheService.getCacheResource(
Long.parseLong(session.getAttribute("idUser").toString()),
component,
deconSecurity().getUser().getSettings().getClientView());
if (cache == null) {
List<ApplicationPagenaviJson> list = null;
File directory = new File(JSON_PATH + "/pagesnavi/");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
try {
String key = files[i].getName().substring(0, files[i].getName().indexOf("."));
byte[] navi = Files.readAllBytes(Paths.get(files[i].getAbsolutePath()));
list = getObjectMapper().readValue(navi, getObjectMapper().getTypeFactory().constructCollectionType(
List.class, ApplicationPagenaviJson.class));
mapper.setPagenaviData(key, list);
} catch (IOException e) {
e.printStackTrace();
}
}
// cache Module Event um die Daten für die Pagenavi nach Rechten zu kontrollieren und entsprechend in den Cache zu speichern
eventDispatcher().dispatch("cleanAndCachePagenaviData", this);
} else {
try {
HashMap<String, List<ApplicationPagenaviJson>> map = getObjectMapper().readValue(
cache.getJsonObject(),
HashMap.class);
mapper.setPagenaviData(map);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Class ApplicationCacheService:
package core.cache.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import core.cache.dao.interfaces.ApplicationCacheDaoInterface;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
import core.cache.service.interfaces.ApplicationCacheServiceInterface;
/**
* Class: ApplicationCacheService
*
* Service Klasse für das verwalten einer Application Cache Speicherung
*
*/
#Service
public class ApplicationCacheService implements ApplicationCacheServiceInterface {
#Autowired
#Qualifier("applicationCacheDao")
private ApplicationCacheDaoInterface cacheDao;
public void saveCacheObject(Object obj) {
cacheDao.saveCacheObject(obj);
}
public boolean isCacheUpdated(Long id, String applicationComponent) {
return cacheDao.isCacheUpdated(id, applicationComponent);
}
public ApplicationCacheModelInterface getCacheResource(Long idUser, String applicationComponent, String applicationType) {
return cacheDao.getCacheResource(idUser, applicationComponent, applicationType);
}
}
Class ApplicationCacheDao:
package core.cache.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import core.base.abstracts.DeconDaoAbstract;
import core.cache.dao.interfaces.ApplicationCacheDaoInterface;
import core.cache.model.ApplicationCacheModel;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
/**
* Class: ApplicationCacheDao
*
* DAO Klasse für das speichern, auslesen und verwalten der ApplicationCache Tabelle
*
*/
#Repository
#Transactional
public class ApplicationCacheDao extends DeconDaoAbstract implements ApplicationCacheDaoInterface {
public void saveCacheObject(Object obj) {
try {
super.getSession().save(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isCacheUpdated(Long id, String applicationComponent) {
boolean isUpdated = false;
String hql = "from ApplicationCacheModel where idUser = " + id + " AND applicationComponent = '" + applicationComponent + "'";
List<ApplicationCacheModel> list = super.getSession().createQuery(hql).list();
if (list.size() == 0) {
isUpdated = true;
} else {
ApplicationCacheModel obj = list.get(0);
if (obj.isUpdate() != false) {
isUpdated = true;
}
}
return isUpdated;
}
public ApplicationCacheModelInterface getCacheResource(Long idUser, String applicationComponent, String applicationType) {
String hql = "from ApplicationCacheModel where idUser = " + idUser + " AND applicationComponent = '" + applicationComponent + "' AND applicationType = '" + applicationType +"'";
List<ApplicationCacheModel> list = super.getSession().createQuery(hql).list();
return (list.size() > 0) ? list.get(0) : null;
}
}
serviceBeans.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:oxm="http://www.springframework.org/schema/oxm"
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-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- User Service -->
<bean id="systemUserService" class="core.security.service.SystemUserService"></bean>
<bean id="systemUserModel" class="core.security.model.SystemUserModel" />
<bean id="systemUserDao" class="core.security.dao.SystemUserDao" />
<!-- SystemRolesService -->
<bean id="systemRoleService" class="core.security.service.SystemRoleService"></bean>
<bean id="systemRoleModel" class="core.security.model.SystemRoleModel"></bean>
<bean id="systemRoleDao" class="core.security.dao.SystemRoleDao"></bean>
<!-- SystemGroupService -->
<bean id="systemGroupService" class="core.security.service.SystemGroupService"></bean>
<bean id="systemGroupModel" class="core.security.model.SystemGroupModel"></bean>
<bean id="systemGroupDao" class="core.security.dao.SystemGroupDao"></bean>
<!-- SystemLanguagesService -->
<bean id="systemLanguagesService" class="core.security.service.SystemLanguagesService"></bean>
<bean id="systemLanguagesModel" class="core.security.model.SystemLanguagesModel"></bean>
<bean id="systemLanguagesDao" class="core.security.dao.SystemLanguagesDao"></bean>
<!-- System Setting Service -->
<bean id="systemSettingsService" class="core.security.service.SystemSettingsService"></bean>
<bean id="systemSettingsModel" class="core.security.model.SystemSettingsModel"></bean>
<bean id="systemSettingsDao" class="core.security.dao.SystemSettingsDao"></bean>
<!-- ApplicationCacheService -->
<bean id="applicationCacheModel" class="core.cache.model.ApplicationCacheModel"></bean>
<bean id="applicationCacheDao" class="core.cache.dao.ApplicationCacheDao"></bean>
<bean id="applicationCacheService" class="core.cache.service.ApplicationCacheService"></bean>
</beans>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
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-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="core.application.controller" />
<context:component-scan base-package="core.security.controller" />
<context:component-scan base-package="core.cache.controller" />
<import resource="database/hibernate.cfg.xml"/>
<import resource="serviceBeans.xml"/>
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"></bean>
<bean id="jsonFactory" class="org.codehaus.jackson.JsonFactory"></bean>
<bean id="mobileJsonMapper" class="core.application.mapper.json.MobileApplicationJson"></bean>
<bean id="desktopJsonMapper" class="core.application.mapper.json.DesktopApplicationJson"></bean>
<bean id="mobileApplicationBuilder" class="core.application.builder.MobileApplicationBuilder">
</bean>
<bean id="desktopApplicationBuilder" class="core.application.builder.DesktopApplicationBuilder"></bean>
<bean id="applicationBuilder" class="core.application.builder.ApplicationBuilder"></bean>
<bean id="deconModuleConfigParser" class="core.base.beans.DeconModuleConfigParser"></bean>
<bean id="deconSessionManager" class="core.base.beans.DeconSessionManager" scope="session"></bean>
<bean id="eventConfigLoader" class="core.event.dispatcher.EventConfigLoader">
<constructor-arg ref="deconModuleConfigParser" />
</bean>
<bean id="eventFactory" class="core.event.dispatcher.EventFactory"></bean>
<bean id="eventDispatcher" class="core.event.dispatcher.EventDispatcher">
<constructor-arg ref="eventFactory" />
<constructor-arg ref="eventConfigLoader" />
</bean>
<bean id="deconSecurity" class="core.base.beans.DeconSecurity"></bean>
<!-- <bean id="sce" class="javax.servlet.ServletContextEvent"></bean> -->
<!-- <import resource="jsonMapperBeans.xml"/> -->
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Decon FM Version 5</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/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>
<listener>
<listener-class>core.base.listeners.DeconSession</listener-class>
</listener>
<servlet>
<servlet-name>Rest Service</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
core.application.controller;
core.security.controller;
core.cache.controller;
org.codehaus.jackson.jaxrs
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Rest Service</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
The Exception message:
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at core.application.builder.MobileApplicationBuilder.buildPagenaviData(MobileApplicationBuilder.java:94)
at core.application.builder.MobileApplicationBuilder.build(MobileApplicationBuilder.java:47)
at core.application.builder.ApplicationBuilder.build(ApplicationBuilder.java:49)
at core.application.controller.ApplicationController.getApplication(ApplicationController.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1480)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1411)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1360)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1350)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Thanks for your help.

I had an overview of your code, I figured the issue. Let me explain why null pointer first.
In your code there are two containers created; Spring and Jersey.
When Jersey is executed you are trying to fetch a bean from spring container, this is not possible , so you need a super container like the (Application Context) to retrieve that bean which is in spring container.
The solution is simple in spring.
Solution : Instead of autowired as dependency injection use this WebApplicationContextUtils.getRequiredWebApplicationContext.getBean(“beanName”);
This is just one way, there are many other ways for dependency injection through Application Context. Try to understand the problem it will help you to get to core of spring bean creation. Rest this solution should work. Cheers

Related

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);
}
}

context.lookup in not working in weblogic

i am new in ejb3 application
my project is:
ServletController.java
package controller;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.HelloUser;
public class ServletController extends HttpServlet {
#Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
try {
InitialContext Context = new InitialContext();
Context context = new InitialContext();
HelloUser helloUser = (HelloUser) context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local");
System.out.println(".................................");
helloUser.sayHello("reza");
arg1.sendRedirect("reza");
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloUser.java:
package com;
import javax.ejb.Local;
#Local
public interface HelloUser {
public void sayHello(String name);
}
HelloUserBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class HelloUserBean implements HelloUser {
public HelloUserBean() {
}
public void sayHello(String name) {
System.out.println("Hello " + name + " welcome to EJB 3!");
}
}
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>Baharan-Framework</display-name>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>controller.ServletController</servlet-class>
</servlet>
</web-app>
the following error is raised when ServletController is called by webbrowser(URL is:http://localhost:7001/weblogic/rest/jkfg):
javax.naming.NameNotFoundException: While trying to lookup 'ejb3.HelloUser/local' didn't find subcontext 'ejb3'. Resolved ''; remaining name 'ejb3/HelloUser/local'
at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
First of all, Weblogic print all jndi names assigned to every Enterprise bean, and you can get it directly. The second, remove context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local"); then in simple cases this function can helps you:
public static <T>T lookupBean(Class<T> beanClass) {
final String jndiName = "java:module/" + beanClass.getSimpleName();
logger.info("lookup : {}", jndiName);
try {
T bean = InitialContext.doLookup(jndiName);
logger.info("detected : {}", bean);
return bean;
}
catch(NamingException e) {
logger.error(e.getMessage(), e);
return null;
}
Can you provide me deployments log?? and rather then trying using initialcontext lookup with #EJB annotation.

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.

#ManagedProperty in a Spring managed bean is null

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>

Resources