autowired dao NullPointerException spring mvc + hibernate [duplicate] - spring

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I'm trying to learn Spring MVC and Hibernate. When I try to run tests I have "Exception in thread "main" java.lang.NullPointerException".
public interface VacancyDAO
package pro.asfert.jobparser.dao;
public interface VacancyDAO {
void LoadDataBase(String query);
void FindVacancy(String queries);}
public class VacancyDAOImpl
package pro.asfert.jobparser.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class VacancyDAOImpl implements VacancyDAO {
#Autowired
private SessionFactory sessionFactory;
public void LoadDataBase(String query) {
sessionFactory.getCurrentSession().createQuery(query);
}
public void FindVacancy(String queries) {
if (queries.contains("По вашему запросу: ")) {
System.out.print(queries);
} else {
sessionFactory.getCurrentSession().createQuery(queries);
}
}
}
public interface VacancyService
package pro.asfert.jobparser.service;
public interface VacancyService {
void LoadDataBase();
void FindVacancy(String queries);
}
**public class VacancyServiceImpl**
package pro.asfert.jobparser.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pro.asfert.jobparser.dao.VacancyDAO;
import pro.asfert.jobparser.domain.Parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
#Service
public class VacancyServiceImpl implements VacancyService {
#Autowired
private VacancyDAO VacancyDAO;
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
/* deleted */
#Transactional
public void LoadDataBase() {
VacancyDAO.LoadDataBase(query);
}
#Transactional
public void FindVacancy(String queries) {
VacancyDAO.FindVacancy(sqlQuery);
}
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:annotation-config />
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="pro.asfert.jobparser.dao"/>
<context:component-scan base-package="pro.asfert.jobparser.service"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value = "${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class = "pro.asfert.jobparser.domain.Vacancy"></mapping>
</session-factory>
</hibernate-configuration>
Vacancy
package pro.asfert.jobparser.domain;
import javax.persistence.*;
#Entity
#Table(name = "Vacancies")
public class Vacancy {
public Vacancy() {
}
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column (name = "vacancy")
private String vacancy;
#Column (name = "salary")
private String salary;
#Column (name = "experience")
private String experience;
#Column (name = "education")
private String education;
#Column (name = "employer")
private String employer;
#Column (name = "details")
private String details;
#Column (name = "hr")
private String hr;
#Column (name = "url")
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVacancy() {
return vacancy;
}
public void setVacancy(String vacancy) {
this.vacancy = vacancy;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

You're creating the service with new here:
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
That way Spring is not involved and does not know anything about this object.
How to fix it:
register your dao and service as spring beans.
initialize the context and get the service from the context and call your method.
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
VacancyServiceImpl serv = ctx.getBean(VacancyServiceImpl.class);
serv.FindVacancy("test");

Related

Spring not roll back transaction if exception throws in the application

I developed the application using spring transactions and insert records in the table.
I'm explicitly throwing the exception in DAO class but spring is inserting the record into the table rather than roll back the transaction.
I have created the two applications as below . In Case 1 record is inserted into table even though exception is thrown . But In Case 2 no record is inserted and spring roll back the transaction successfully. Can you explain me the difference between these two applications.
Case 1:
Item.java
public class Item {
int itemNo;
String itemName;
String itemType;
String itemSize;
public int getItemNo() {
return itemNo;
}
public void setItemNo(int itemNo) {
this.itemNo = itemNo;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemSize() {
return itemSize;
}
public void setItemSize(String itemSize) {
this.itemSize = itemSize;
}
}
ItemDao
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
try{
itemDao.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct = new ClassPathXmlApplicationContext("spring.xml");
ItemService itemService = ct.getBean("itemService", ItemService.class);
Item item = new Item();
item.setItemNo(1234);
item.setItemName("sofa");
item.setItemSize("4");
item.setItemType("furniture");
itemService.insert(item);
}
}
spring.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:tx="http://www.springframework.org/schema/tx" 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.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">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<context:component-scan base-package="com.spring.springtransaction" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type
DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- MySQL DB DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#locahost:1521:xe)))" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="itemService" class="com.spring.springtransaction.ItemService" />
</beans>
Case 2:
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Autowired
ItemManger itemManger;
#Transactional
public void insert(Item item){
try{
itemManger.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
ItemManger.java
#Service
public class ItemManger {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
itemDao.insert(item);
}
}
ItemDao.java
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
Annotate you ItemDao as #Repository instead of #Service
You should execute unit test with spring Transactional context instead of main , for example using TestNG:
#ContextConfiguration(classes = {ConfigurationClass.class})
#ActiveProfiles({"test"})
public class TestItemDAO extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private ItemDao dao;
#Test
public void testItemDao() {
dao.insert(item);
}
}
Remove the try block, you are trying to handle the exception so this is reason why RollbackException is not cutting the transaction stream.

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

Spring service layer object comes null

Hi I am learning Spring and has stuck to a problem.
I have a structure something like the following:
package com.edfx.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CUSTOMER")
public class Customer {
private long customer_id;
private String name;
private String address;
private Date created_date;
#Id
#Column(name = "CUSTOMER_ID")
public long getCustomer_id() {
return customer_id;
}
public void setCustomer_id(long customer_id) {
this.customer_id = customer_id;
}
#Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "CREATED_DATE")
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
#Override
public String toString(){
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("customer_id:").append(getCustomer_id());
strBuffer.append(", name : ").append(getName());
strBuffer.append(", address: ").append(getAddress());
strBuffer.append(", created_date: ").append(getCreated_date());
return strBuffer.toString();
}
}
The Managed Bean is:
package com.edfx.managedbean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import org.springframework.dao.DataAccessException;
import com.edfx.customer.service.ICustomerService;
import com.edfx.model.Customer;
#ManagedBean(name = "customerMB")
#SessionScoped
public class CustomerManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8839370045113377019L;
private static final String SUCCESS = "success";
private static final String ERROR = "error";
// Spring Customer Service Injection
ICustomerService customerService;
public ICustomerService getCustomerService() {
System.out.println("customerService -- >"+customerService);
return customerService;
}
public void setCustomerService(ICustomerService customerService) {
this.customerService = customerService;
}
List<Customer> userList;
private long customer_id;
private String name;
private String address;
private Date created_date;
public String addUser(){
System.out.println("Managed Bean Add User..");
try {
Customer customer = new Customer();
System.out.println("ID :: "+getCustomer_id());
customer.setCustomer_id(getCustomer_id());
System.out.println("Name :: "+getName());
customer.setName(getName());
System.out.println("Address :: "+getAddress());
customer.setAddress(getAddress());
System.out.println("Created Date :: "+new Date());
customer.setCreated_date(new Date());
//Service Provider
getCustomerService().addUser(customer);
return SUCCESS;
} catch (DataAccessException e) {
System.err.println("Error Occured :: "+e.getMessage());
}
return ERROR;
}
public void reset(){
this.setCustomer_id(0);
this.setName("");
this.setAddress("");
this.setCreated_date(null);
}
public List<Customer> getUserList(){
userList = new ArrayList<Customer>();
System.out.println("BEAN :: "+getCustomerService().getUsers());
userList.addAll(getCustomerService().getUsers());
return userList;
}
public void setUserList(List<Customer> userList) {
this.userList = userList;
}
public long getCustomer_id() {
return customer_id;
}
public void setCustomer_id(long customer_id) {
this.customer_id = customer_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
}
The applicationContextFile is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.edfx.managedbean"/>
<context:annotation-config/>
<!-- Bean Declaration -->
<bean id="Customer" class="com.edfx.model.Customer"/>
<!-- Customer Service Declaration -->
<bean id="customerService" class="com.edfx.customer.service.CustomerService" scope="prototype">
<property name="customerDAO" ref="CustomerDAO"/>
</bean>
<!-- Customer DAO Declaration -->
<bean id="CustomerDAO" class="com.edfx.customer.dao.CustomerDAO">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<!-- Data Source Declaration -->
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatements" value="0"/>
<property name="minPoolSize" value="5"/>
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<property name="annotatedClasses">
<list>
<value>com.edfx.model.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behaviour based on annotation -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Transaction Manager is defined -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="runMeJob"/>
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
<!-- Spring Configuration Manager -->
<bean id="runMeTask" class="com.edfx.customer.schedular.RunMeTask"/>
<!-- Spring Quartz -->
<bean name="runMeJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.edfx.customer.schedular.RunMeJob"/>
<property name="jobDataAsMap">
<map>
<entry key="runMeTask" value-ref="runMeTask"/>
</map>
</property>
</bean>
<!-- Simple Trigger every 5 secs
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="runMeJob"/>
<property name="repeatInterval" value="5000"/>
<property name="stratDelay" value="1000"/>
</bean> -->
<!-- CronTrigger runs every 5 secs-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="runMeJob"/>
<property name="misfireInstructionName" value="MISFIRE_INSTRUCTION_FIRE_ONCE_NOW" />
<property name="cronExpression" value="0 30 19 * * ?"/>
</bean>
Here I have set a schedular. The scheduler works absolutely fine as it fires properly at the specific time.
Here is the Job details that is scheduled to run:
package com.edfx.customer.schedular;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.naming.directory.Attributes;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.ContextLoader;
import com.edfx.customer.ldap.mngr.LDAPManager;
import com.edfx.customer.service.CustomerService;
import com.edfx.customer.service.ICustomerLdapSyncService;
import com.edfx.customer.service.ICustomerService;
import com.edfx.managedbean.CustomerManagedBean;
import com.edfx.model.Customer;
public class RunMeJob extends QuartzJobBean{
private RunMeTask runMeTask;
#Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
ApplicationContext applicationContext = null;
try {
applicationContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
} catch (Exception e) {
System.err.println("Synchronization Error :: "+e.getMessage());
}
if(applicationContext == null)
applicationContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("=============== SCHEDULAR SERVICE ON =================");
System.out.println("MAP DETAILS == >"+new LDAPManager().getUserDetails());
Map<String, String> userDetailsMap = new LDAPManager().getUserDetails();
CustomerManagedBean customerManagedBean = new CustomerManagedBean();
int i=0;
for(Map.Entry<String, String> entry : userDetailsMap.entrySet()){
i++;
String key = entry.getKey();
String value = entry.getValue();
System.out.println("Key -->"+key+" :: Value-->"+value);
customerManagedBean.setCustomer_id(i);
customerManagedBean.setName(key);
customerManagedBean.setAddress(value);
customerManagedBean.setCreated_date(new Date());
}
customerManagedBean.addUser();
runMeTask.printMe();
System.out.println("=============== SCHEDULAR SERVICE OFF ================");
}
public void setRunMeTask(RunMeTask runMeTask) {
this.runMeTask = runMeTask;
}
}
Here, the method addUser() invokes properly. But while executing getCustomerService().addUser(customer); it throws NullPointerException as it gets customerService object null, which has been injected in the CustomerManagedBean class. mentioned in applicationContext.xml.
What could be the possible reason for this?
Please Help!
First problem I found is that, in your executeInternal method you are not using customerManagedBean from your Spring application context. Instead of that, you are creating one like bellow:
CustomerManagedBean customerManagedBean = new CustomerManagedBean();
And when you are creating your own bean, its your responsibility to prepare it before use (injection or initialization), because you are not using it from any context made and managed by any framework (Spring or something else). You could avoid these problems by simply getting the bean from Spring's ApplicationContext, by replacing the above line with the line bellow:
CustomerManagedBean customerManagedBean = (CustomerManagedBean)applicationContext.getBean("beanName")
Second thing,
Are you using JSF with Spring?
If your answer is no, then why you are using JSF annotations (#ManagedBean and #SessionScoped). As these annotations are not recognizable to Spring. Spring actually doesn't instantiate it in its context. Although you putted,
<context:component-scan base-package="com.edfx.managedbean"/>
in your applicationContext.xml.
If your answer is yes, then you should follow, the following tutorials properly to configure successfully:
jsf 2.0 spring integration example
jsf 2.0 spring hibernate integration example

nullpointer exception in getcurrentsession

I am trying to integrate Hibernate 4.1 with Spring 3.1.3.
//configuration file (beans.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: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 ">
<bean id="employeeDAObean" class="com.Hib_Spring.EmployeeDAO">
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="annotatedClasses" value="com.Hib_Spring.Employee"> </property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/newdatabase"/>
<property name="username" value="postgres"/>
<property name="password" value="P#ssword"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
</beans>
This is my model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee_new")
public class Employee {
#Id
#Column(name="ID")
private int id;
#Column (name="firstname")
private String first_name;
#Column(name="lastname")
private String last_name;
public Employee() {}
public Employee(int id,String fname, String lname) {
this.first_name = fname;
this.last_name = lname;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName( String first_name ) {
this.first_name = first_name;
}
public String getLastName() {
return last_name;
}
public void setLastName( String last_name ) {
this.last_name = last_name;
}
}
Following is my DAO class
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class EmployeeDAO {
#Autowired
SessionFactory sessionFactory;
public void createEmployee(int id, String fname, String lname)
{
Employee emp1 = new Employee(id,fname,lname);
sessionFactory.getCurrentSession().save(emp1);
}
public List getAllEmployees(){
return sessionFactory.getCurrentSession().createQuery("from employee_new").list();
}
}
My table has three columns ID, firstname,lastname
This is the main class(Client.java)
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String arg[]){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
EmployeeDAO employeedao=context.getBean("employeeDAObean",EmployeeDAO.class);
System.out.println("Entering data in the database");
employeedao.createEmployee(101, "aaa", "bbb");
employeedao.createEmployee(102, "ccc", "ddd");
System.out.println("Reading the data");
List employeelist= employeedao.getAllEmployees();
for(int i=0;i<employeelist.size();i++){
Employee e = (Employee) employeelist.get(i);
System.out.println("Emp No "+e.getId());
System.out.println("FirstName "+e.getFirstName());
System.out.println("LastName "+e.getLastName());
}
}
}
Now my problem is that whenever I try to execute client.java I am getting a nullpointer exception in
sessionFactory.getCurrentSession().save(emp1);
of the EmployeeDAO class.
Right now my table is empty and I am trying to add a record in it. I dont what is the exact mistake I have done. I am sure there should be a silly one. Could someone throw some light on it. Thanks for the help!
You have tx:annotation-driven but I do not see any transaction annotations. Try putting the annotation on the createEmployee method of the dao and that will get it going.

Basic spring issue : using #Autowired

I have the following 2 objects: User and DomainUser
User.java:
package com.domain;
import java.io.Serializable;
#SuppressWarnings("serial")
public class User implements Serializable {
private long id = 0;
private String userName;
private String password;
public User() {
}
public User(long id) {
this.id = id;
}
public String toString() {
StringBuffer sb = new StringBuffer(256);
sb.append("[id : ").append(id).append(", ");
sb.append("userName : ").append(userName).append(", ");
sb.append("password : ").append(password).append("]");
return sb.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DomainUser.java
package com.domain;
import org.springframework.beans.factory.annotation.Autowired;
public class DomainUser {
#Autowired
private User user;
private String domainName;
public String toString() {
StringBuffer sb = new StringBuffer(255);
sb.append(user.toString()).append(", domainName : ").append(domainName);
return sb.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
I am trying to autowire the User object in to DomainUser by using #Autowired annotation. But when i run the test as below, the User object is not populated.
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="user" class="com.domain.User">
<constructor-arg value="#{1234}"/>
<property name="userName" value="somename" />
<property name="password" value="sompassword" />
</bean>
<bean id="domainUser" class="com.domain.DomainUser">
<property name="domainName" value="mysite" />
</bean>
</beans>
DomainUserTest.java
package com.domain.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.DomainUser;
public class DomainUserTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
DomainUser domainUser = (DomainUser) context.getBean("domainUser");
System.out.println(domainUser.toString());
}
}
If I autowire using the 'byType' in the autowiring attribute in the applicationContext.xml it works fine :
<bean id="domainUser" class="com.domain.DomainUser" autowire="byType">
<property name="domainName" value="mysite" />
</bean>
Can some one help me understand why doesnt #Autowired annotation produce the same result?
You need an AutowiredAnnotationBeanPostProcessor to handle the injection of #Autowired properties. You could place <context:annotation-config /> (you need to define the context-namespace in your xml) or just define the post processor as a bean in your xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
See for example here for details.

Resources