with this config for Spring framework (4.2.5.RELEASE version):
<bean id="Filter" class="net....StreamFilter" abstract="true">
<property name="begin" value="3" />
<property name="end" value="5" />
</bean>
<bean id="D0Filter" parent="Filter">
<property name="value" value="D0" />
</bean>
and my StreamFilter class is like:
public class StreamFilter {
/** debut du filtre */
private int begin;
/** fin du filtre */
private int end;
private String value;
public Object convert(#Body final Exchange exchange) {
// my code
}
//
// getter & setter
//
}
i have this error:
Exception in thread "main"
org.springframework.beans.factory.BeanIsAbstractException: Error
creating bean with name 'DFIFilter': Bean definition is abstract at
org.springframework.beans.factory.support.AbstractBeanFactory.checkMergedBeanDefinition(AbstractBeanFactory.java:1288)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:285)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
......
thanks for your responses
Related
I want to configure below type of bean initialization to be performed by annotation.
Below is sample bean configuration in xml type and want to configure this kind of bean using annotations.
<bean id="Animal" class="aaa.type.Animal">
<property name="Animal" value="${Animal}" />
<property name="AnimalFamily" >
<bean class="aaa.type.AnimalFamily">
<property name="AnimalCharactertitic">
<list>
<bean class="aaa.type.AnimalColor">
<property name="name" value="Color" />
<property name="value" value="${color}" />
</bean>
<bean class="aaa.type.AnimalType">
<property name="name" value="Animal Type" />
<property name="value" value="${AnimalType}" />
</bean>
</list>
</property>
</bean>
</property>
</bean>
You can do something like this:
#Configuration
public class MyConfigurationClass {
#Bean
public AnimalCharactertitic animalColor(#Value("${color}") String color) {
AnimalCharactertitic animalCharactertitic = new AnimalCharactertitic();
animalCharactertitic.setName("Color");
animalCharactertitic.setValue(color);
return animalCharactertitic;
}
#Bean
public AnimalCharactertitic animalType(#Value("${AnimalType}") String animalType) {
AnimalCharactertitic animalCharactertitic = new AnimalCharactertitic();
animalCharactertitic.setName("Animal Type");
animalCharactertitic.setValue(animalType);
return animalCharactertitic;
}
#Bean
public AnimalFamily animalFamily(#Autowired AnimalCharactertitic animalColor,
#Autowired AnimalCharactertitic animalType) {
AnimalFamily animalFamily = new AnimalFamily();
List<AnimalCharactertitic> animalCharactertitics = new ArrayList<>();
animalCharactertitics.add(animalColor);
animalCharactertitics.add(animalType);
animalFamily.setAnimalCharactertitic(animalCharactertitics);
return animalFamily;
}
#Bean
public Animal animal(#Value("${Animal}") String animal, #Autowired AnimalFamily animalFamily) {
Animal animal = new Animal();
animal.setAnimal(animal);
animal.setAnimalFamily(animalFamily);
return animal;
}
}
We are working on a Tapestry5-Spring-Hibernate application.
We are using Tapestry 5.4.1, Spring 4.3.1.RELEASE and Hibernate 4.3.6.Final.
We are using and XML based application.
We are facing the problem that all daos #Autowired into spring services are always null. This will of course generate a NullpointerException everytime a dao is needed to perform an operation on the database.
We used generic service and dao interfaces
Here are the code samples:
Spring config file
<context:annotation-config />
<context:component-scan base-package="org.prism.forecast" />
<context:property-placeholder location="classpath:hibernate.properties" />
<!--Generic DAO -->
<bean id="appDao" primary="true" class="org.prism.forecast.dao.AppDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!--Generic service-->
<bean id="appServiceImpl" class="org.prism.forecast.services.AppServiceImpl">
<property name="dao">
<ref bean="appDao" />
</property>
</bean>
<bean id="requestDao" class="org.prism.forecast.dao.RequestDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="requestServiceImpl" class="org.prism.forecast.services.RequestServiceImpl">
<property name="dao">
<ref bean="requestDao" />
</property>
</bean>
<bean id="SOPUploadDao" class="org.prism.forecast.dao.SOPUploadDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="SOPUploadServiceImpl" class="org.prism.forecast.services.SOPUploadServiceImpl">
<property name="dao">
<ref bean="SOPUploadDao" />
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.prism.forecast.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="txManager"/>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
Generic DAO Interface
public interface AppDao {
/**
* Finds an object by id
*
* #param <T>
* #param <PK>
* #param type
* #param id
* #return the object
*/
<T, PK extends Serializable> T find(Class<T> type, PK id);
//other methods
}
Generic DAO implementation
#Repository("appDao")
public class AppDaoImpl implements AppDao {
protected static final Logger logger = LoggerFactory.getLogger(RequestDaoImpl.class);
#Inject
protected Session session;
#Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
/**
* #param sessionFactory the sessionFactory to set
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public <T, PK extends Serializable> T find(Class<T> type, PK id) {
return (T) session.get(type, id);
}
//other methods
}
Request DAO
public interface RequestDao extends AppDao {
}
Request DAO Implementation
#Repository("requestDao")
public class RequestDaoImpl extends AppDaoImpl implements RequestDao {
}
Generic service
public interface AppService {
/**
* #param <T>
* #param <PK>
* #param type
* #param id
* #return the object
*/
<T, PK extends Serializable> T find(Class<T> type, PK id);
//Other methods
}
Generic service implementation
#Service("appService")
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class AppServiceImpl implements AppService {
#Autowired
private AppDao dao = null;
/**
* #return the dao
*/
public AppDao getDao() {
return dao;
}
/**
* #param dao
* the dao to set
*/
public void setDao(AppDao dao) {
this.dao = dao;
}
#Override
public <T, PK extends Serializable> T find(Class<T> type, PK id) {
return dao.find(type, id);//dao is null here
}
//other methods
}
Request Service
public interface RequestService extends AppService {
}
Request Service Implementation
#Service("requestService")
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class RequestServiceImpl extends AppServiceImpl implements RequestService {
#Autowired
private RequestDao dao;
#Override
public Request find(Request request) {
dao.find(request);
}
//other methods
}
Usage in Tapestry pages
public class ManageRequest{
//dao needed for persistence operations
#InjectService("requestService")
protected requestService service;
}
While debugging the application we figured out that the service has been properly injected into the page but the dao has not been injected into the service. Can anybody tell me what is going wrong here?
This looks like Spring configuration issue, could it be that you need to specify sub package of your DAO services explicitly in <context:component-scan ... />, i.e.:
<context:component-scan base-package="org.prism.forecast, org.prism.forecast.dao" />
Some hints: #Autowired service is null, and multiple packages in context:component-scan.
Hi below is my configuration for creating asynchlob launcher
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="&jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" />
i'm getting below error
Error creating bean with name 'batchJobLauncher': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.launch.support.SimpleJobLauncher com.batch.launcher.BatchJobLauncher.asyncJobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/BatchConfig.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
.....
caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1482) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 54 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:461) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 60 more
i tried without & also.
error like this
13:58:59,346 WARN [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 58) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.configuration.annotation.JobBuilderFactory]: Factory method 'jobBuilders' threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$99e29281 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
Here is a working example made from http://www.mkyong.com/spring-batch/spring-batch-hello-world-example/ and tested on wildfly 9.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
">
<bean id="report" class="Report" scope="prototype" />
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<batch:job id="helloWorldJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="cvsItemReader" writer="xmlItemWriter"
commit-interval="10">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="cvsItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="classpath:report.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id,sales,qty,staffName,date" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="report" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:/home/username/report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="report" />
</bean>
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>Report</value>
</list>
</property>
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
</beans>
Report.java:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "record")
public class Report {
private int id;
private String sales;
private int qty;
private String staffName;
private String date;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "sales")
public String getSales() {
return sales;
}
public void setSales(String sales) {
this.sales = sales;
}
#XmlElement(name = "qty")
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#XmlElement(name = "staffName")
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "Report [id=" + id + ", sales=" + sales
+ ", qty=" + qty + ", staffName=" + staffName + "]";
}
}
To run use a servlet with the following code:
ApplicationContext context =
new ClassPathXmlApplicationContext("job.xml");
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("helloWorldJob");
try {
org.springframework.batch.core.JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
My config:
<bean parent="cache-template">
<property name="name" value="yagoLabel" />
<property name="cacheMode" value="PARTITIONED" />
<property name="atomicityMode" value="TRANSACTIONAL" />
<property name="distributionMode" value="PARTITIONED_ONLY" />
<property name="backups" value="1" />
<property name="store">
<bean class="id.ac.itb.ee.lskk.lumen.yago.YagoLabelCacheStore" autowire="byType" init-method="init" />
</property>
<property name="writeBehindEnabled" value="true" />
<property name="writeBehindFlushSize" value="102380" />
<property name="writeBehindFlushFrequency" value="30000" />
<property name="writeBehindBatchSize" value="10240" />
<property name="swapEnabled" value="false" />
<property name="evictionPolicy">
<bean class="org.gridgain.grid.cache.eviction.lru.GridCacheLruEvictionPolicy">
<property name="maxSize" value="102400" />
</bean>
</property>
</bean>
And I start GridGain as follows:
My GridCacheStore implementation:
public class YagoLabelCacheStore extends GridCacheStoreAdapter<String, YagoLabel> {
private static final Logger log = LoggerFactory
.getLogger(YagoLabelCacheStore.class);
private DBCollection labelColl;
#GridSpringResource(resourceName="mongoDb")
private DB db;
#Inject
private GridGainSpring grid;
#PostConstruct
public void init() {
log.info("Grid is {}", grid);
labelColl = db.getCollection("label");
}
I start GridGain as follows:
String entityId = "Muhammad";
try (AnnotationConfigApplicationContext appCtx
= new AnnotationConfigApplicationContext(LumenConfig.class)) {
Grid grid = appCtx.getBean(Grid.class);
GridCache<String, YagoLabel> labelCache = YagoLabel.cache(grid);
log.info("Label for {}: {}", entityId, labelCache.get(entityId));
}
LumenConfig Spring configuration contains a DB bean named mongoDb.
However this throws NullPointerException because db is not injected properly. I tried #Inject GridGainSpring just for testing, and even GridGainSpring itself is not injected.
I also tried setting <property name="db" ref="mongoDb"/> in the GridGain Config XML but Spring complains cannot find the bean.
My workaround is to put it inside a public static field but that's soo hacky: https://github.com/ceefour/lumen-kb/blob/b8445fbebd227fb7ac337c758a60badb7ecd3095/cli/src/main/java/id/ac/itb/ee/lskk/lumen/yago/YagoLabelCacheStore.java
The way is to load the GridConfiguration using Spring, then pass it to GridGainSpring.start() :
// "classpath:" is required, otherwise it won't be found in a WAR
#ImportResource("classpath:id/ac/itb/ee/lskk/lumen/core/lumen.gridgain.xml")
#Configuration
public static class GridGainConfig {
#Inject
private ApplicationContext appCtx;
#Inject
private GridConfiguration gridCfg;
#Bean(destroyMethod="close")
public Grid grid() throws GridException {
return GridGainSpring.start(gridCfg, appCtx);
}
}
:-)
I am doing spring + hibernate apllication. When I run the application on tomcat server I am getting some exception. Below is my code.
This is my bean config file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/database/db.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<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 bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
</bean>
<bean id="employeeBo" class="com.saggezza.employee.bo.impl.EmployeeBoImpl">
<property name="employeeDao" ref="employeeDao" />
</bean>
<bean id="employeeDao" class="com.saggezza.employee.dao.impl.EmployeeDaoImpl">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
this is my dao class.
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
private SessionFactory sessionFactory;
public EmployeeDaoImpl(SessionFactory sessionfactory){
this.sessionFactory=sessionfactory;
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
Here another class employeeBo is calling the employeeDaoImpl.
when I run thisI am getting the below exception.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBo' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Cannot resolve reference to bean 'employeeDao' while setting bean property 'employeeDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
Can anybody help to resolve this. I have tried a lot and google it as well.But did get the solution.
If you have two configuration files, you duplicates 'sessionFactory' definition. Remove one of the 'sessionFactory' definitions . You would have got duplicate bean definition exception before the IllegalArgumentException.
Edit: After your comment,
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
public EmployeeDaoImpl(SessionFactory sessionfactory){
setSessionFactory(sessionfactory);
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
or get rid of constructor in above code and inject 'sessionFactory' using setter injection.See org.springframework.orm.hibernate3.support.HibernateDaoSupport.setSessionFactory(SessionFactory). I prefer later approach.
I think the problem is the type of SessionFactory you are injecting in EmployeeDaoImpl does not match with the type of the SessionFactory you used in the class.
Can you check it?
This is an old question so must be solved now but still if someone comes across this problem. Following is solution.
You can use Hibernate DAO Support by extending HibernateDAOSupport class and overriding its afterPropertiesSet() method.
This method is called in HibernateDAO support and at that time since sessionFactory is null it is throwing this error. In your custom class you can set this property explicitly and then call the same method of Parent Class (i.e. HibernateDAOSupport's addProperties() method)
package com.techcielo.spring4.hibernate.template;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
#Component("hibernateTemplate")
public class Hibernate4CustomTemplate extends HibernateTemplate{
#Autowired(required=true)
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
System.out.println("Setting SessionFactory");
this.sessionFactory = sessionFactory;
super.setSessionFactory(sessionFactory);
}
#Override
public void afterPropertiesSet() {
System.out.println("Checking if properties set..."+this.sessionFactory);
setSessionFactory(sessionFactory);
super.afterPropertiesSet();
}
}
Following can be used for sample!
I had the same problem and fix it by using Autowired constructor with EntityManagerFactory. Keyur answer is correct
#Service
class EmployeeDaoImpl #Autowired constructor(
factory: EntityManagerFactory
) : HibernateDaoSupport(), EmployeeDao {
init {
if (factory.unwrap(SessionFactory::class.java) == null) {
throw NullPointerException("factory is not a hibernate factory")
}
setSessionFactory(factory.unwrap(SessionFactory::class.java))
}
...
}