Hibernate/Spring - AnnotationSessionFactoryBean - how to resolve duplicate import? - spring

I'm having a problem in a Spring Configuration creating a bean which extends AnnotationSessionFactoryBean.
Here's the definition of the class:
public class ExtendedAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean {
private String[] basePackages;
private ClassLoader beanClassLoader;
#Override
public void afterPropertiesSet() throws Exception {
System.out.println("ExtendedAnnotationSessionFactoryBean, in afterPropertiesSet");
Collection<Class<?>> entities = new ArrayList<Class<?>>();
ClassPathScanningCandidateComponentProvider scanner = this.createScanner();
for (String basePackage : this.basePackages) {
this.findEntities(scanner, entities, basePackage);
}
this.setAnnotatedClasses(entities.toArray(new Class<?>[entities.size()]));
super.afterPropertiesSet();
}
private ClassPathScanningCandidateComponentProvider createScanner() {
System.out.println("ExtendedAnnotationSessionFactoryBean, in createScanner");
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
return scanner;
}
private void findEntities(ClassPathScanningCandidateComponentProvider scanner,
Collection<Class<?>> entities, String basePackage) {
System.out.println("ExtendedAnnotationSessionFactoryBean, in findEntities");
Set<BeanDefinition> annotatedClasses = scanner.findCandidateComponents(basePackage);
for (BeanDefinition bd : annotatedClasses) {
String className = bd.getBeanClassName();
System.out.println("ExtendedAnnotationSessionFactoryBean, className: " + className);
Class<?> type = ClassUtils.resolveClassName(className, this.beanClassLoader);
entities.add(type);
}
}
public void setBasePackage(String basePackage) {
this.basePackages = new String[]{basePackage};
}
public void setBasePackages(String[] basePackages) {
this.basePackages = basePackages;
}
#Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
}
Here's how it's configured:
<b:bean id="sessionFactory" class="com.mycompany.spring.ExtendedAnnotationSessionFactoryBean">
<b:property name="dataSource" ref="dataSource" />
<b:property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
<b:property name="hibernateProperties" ref="hibernateProperties" />
<b:property name="entityInterceptor" ref="baseEntityInterceptor" />
<b:property name="basePackages">
<b:list>
<b:value>com.mycompany.entities</b:value>
<b:value>com.mycompany.entities1_1</b:value>
</b:list>
</b:property>
</b:bean>
The source code in each package (com.mycompany.entities, com.mycompany.entities1_1) is identical except that the catalog is defined in the second one:
#Table(catalog="myDatabase1_1", name = "mytablename1")
When I run a test I get a crash with a stack trace which states that the same entity name is being used twice (although they are in different packages). At the end of the stack trace, it suggests setting the "auto-import" to false:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyTableName1 refers to both com.mycompany.entities1_1.MyTableName1 and com.mycompany.entities.MyTableName1 (try using auto-import="false")
Questions: What auto-import mean, why would it work, and where would I specify it?
Here's the entire stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [file:WEB-INF/myconfiguration.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of the same entity name twice: MyTableName1
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [file:WEB-INF/myconfiguration.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of the same entity name twice: MyTablenNme1
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.nuval.infrastructure.test.BaseTest.init(BaseTest.java:44)
at com.nuval.infrastructure.test.BaseTest.setUp(BaseTest.java:62)
at com.nuval.test.CloneTest.setUp(CloneTest.java:104)
at junit.framework.TestCase.runBare(TestCase.java:125)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.AnnotationException: Use of the same entity name twice: MyTableName1
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:347)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:613)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:636)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:359)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:673)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at com.zeer.onqi.spring.ExtendedAnnotationSessionFactoryBean.afterPropertiesSet(ExtendedAnnotationSessionFactoryBean.java:36)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
... 30 more
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyTableName1 refers to both com.mycompany.entities1_1.MyTableName1 and com.mycompany.entities.MyTableName1 (try using auto-import="false")
at org.hibernate.cfg.Configuration$MappingsImpl.addImport(Configuration.java:2418)
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:340)
... 39 more

Your problem is not related to your bean and is caused by the fact that you have two entities with the same logical name in your SessionFactory. It means that Hibernate won't be able to understand which entity should it use in query such as from MyTableName1.
If you really need to have these entities in the same SessionFactory simultaneously, you should specify different logical names for them, as follows:
#Entity(name = "MyTableName1")
#Table(...)
public class MyTableName1 { ... }
#Entity(name = "MyTableName1_1")
#Table(...)
public class MyTableName1 { ... }
and use these names in HQL queries.
If you don't need them simultaneously, perhaps you can put them into different SessionFactories for different schemas.
Also note that, as far as I understand, you don't need to create your own subclass of AnnotationSessionFactoryBean, because the default one supports the same functionality as you try to achieve, see packagesToScan property.

Related

Getting error while dynamically providing input,output path

I have created a multi-file reader and flat file writer (Later, I have to extend it to multifile read to multiple file write, one to one mapping). When i provide the input path through property file, It works all good, but when I try to provide path through jobExecutionContext it starts giving me error. What surprises me is that writer is successfully taking the path from executionContext and writing whatever location i provide but not the reader.
PS: I am using "SingleItemPeekableItemReader" because the data i have in file is multi-line record and has no way to determine when one record ends . the only way to know that record 2 has started is when you have access to next line and you know that its start of new record.
Can someone through some light, What wrong i am doing.
<bean id="itemReader" class="com.varun.reader.AccountDataReader">
<property name="fieldSetReader" ref="PeekableitemReader" />
<property name="headerFieldSetMapper" ref="headerFieldSetMapper" />
<property name="multiReader" ref="multiResourceReader"/>
</bean>
<bean id="PeekableitemReader" class="org.springframework.batch.item.support.SingleItemPeekableItemReader" >
<property name="delegate" ref="multiResourceReader"/>
</bean>
<bean id="multiResourceReader" class=" org.springframework.batch.item.file.MultiResourceItemReader" >
<property name="resources" value="file:${file.input.dir}*.DAT" />
<property name="delegate" ref="fileItemReader" />
</bean>
<bean id="fileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer" ref="accountDataTokenizer"/>
<property name="fieldSetMapper">
<bean class="org.springframework.batch.item.file.mapping.PassThroughFieldSetMapper" />
</property>
</bean>
</property>
<property name="comments" value=""></property>
</bean>
It error out, when i provide the resources in multiresourceReader as below
<property name="resources" value="file:#{JobExecutionContext[input_dir]}*.DAT" />
Error logs as below:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'itemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemReader' defined in class path resource [spring/config/process-config.xml]: Cannot resolve reference to bean 'PeekableitemReader' while setting bean property 'fieldSetReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'PeekableitemReader' defined in class path resource [spring/config/process-config.xml]: Cannot resolve reference to bean 'multiResourceReader' while setting bean property 'delegate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'multiResourceReader' defined in class path resource [spring/config/process-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'JobExecutionContext' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
after making multireader scope as step i am getting error as below.I have tried putting scope on all the other delegate readers as well, but i am getting the same error.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'itemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemReader' defined in class path resource [spring/config/process-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type [com.sun.proxy.$Proxy11 implementing org.springframework.batch.item.ItemStreamReader,org.springframework.batch.item.ItemStream,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.MultiResourceItemReader] for property 'multiReader'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy11 implementing org.springframework.batch.item.ItemStreamReader,org.springframework.batch.item.ItemStream,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.MultiResourceItemReader] for property 'multiReader': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.varun.JobScheduler.main(JobScheduler.java:9)
My custom Reader
public class AccountDataReader implements ItemReader<AccountDataBO> {
private static Log log = LogFactory.getLog(AccountDataReader.class);
private boolean recordFinished;
private AccountDataBO acctObj = new AccountDataBO();
private SingleItemPeekableItemReader<FieldSet> fieldSetReader;
private HeaderFieldSetMapper headerFieldSetMapper;
private MultiResourceItemReader<FieldSet> multiReader;
#Override
public AccountDataBO read() throws Exception {
recordFinished = false;
while (!recordFinished) {
process(fieldSetReader.read());
}
AccountDataBO result = acctObj;
acctObj = new AccountDataBO();
return result;
}
private void process(FieldSet fieldSet) throws Exception {
if (fieldSet == null) {
log.debug("FINISHED Reading");
recordFinished = true;
acctObj=null;
return;
}
String lineId = fieldSet.readString(0);
if (!StringUtils.isEmpty(lineId) && lineId.contains(AccountDataBO.ACCOUNT)) {
log.debug("Starting new Record");
acctObj.setHeader(headerFieldSetMapper.mapFieldSet(fieldSet));
acctObj.setResource(multiReader.getCurrentResource());
}
//Code
}
private void CheckEOFNewAccount() throws Exception {
if ((fieldSetReader.peek() != null
&& ((fieldSetReader.peek().getValues())[0].contains(AccountDataBO.ACCOUNT)))
|| fieldSetReader.peek() == null) {
log.debug("Next Line is Account or EOF Hence returning for current Account");
recordFinished = true;
return;
}
}
public void setFieldSetReader(SingleItemPeekableItemReader<FieldSet> fieldSetReader) {
this.fieldSetReader = fieldSetReader;
}
public void setHeaderFieldSetMapper(HeaderFieldSetMapper headerFieldSetMapper) {
this.headerFieldSetMapper = headerFieldSetMapper;
}
public void setMultiReader(MultiResourceItemReader<FieldSet> multiReader) {
this.multiReader = multiReader;
}
}
In order to inject job parameters into a batch component, the component needs to be step scoped. So in your example, change this:
<bean id="multiResourceReader"
class=" org.springframework.batch.item.file.MultiResourceItemReader" >
To this:
<bean id="multiResourceReader"
class=" org.springframework.batch.item.file.MultiResourceItemReader"
scope="step" >

Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource

I am new to Spring. I am creating simple project in which I just call generateOutout() method using beans.
IOutputGenerator Interface:
package mian.java;
public interface IOutputGenerator {
public void generateOutput();
}
CsvOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class CsvOutputGenerator implements IOutputGenerator{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
JsonOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
OutputHelper.java:
package mian.java;
public class OutputHelper {
IOutputGenerator outputGeneratorCsv;
IOutputGenerator outputGeneratorJson;
public void generateOutput(){
outputGeneratorCsv.generateOutput();
outputGeneratorJson.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGeneratorCsv,IOutputGenerator outputGeneratorJson){
this.outputGeneratorCsv = outputGeneratorCsv;
this.outputGeneratorJson = outputGeneratorJson;
}
}
AppViaSpring.java (Main class):
package mian.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppViaSpring {
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Spring-Common.xml (Bean Class in main.resources package):
<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 id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="main.java.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="main.java.JsonOutputGenerator" />
</beans>
and Error is :
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource [Spring-Common.xml]; nested exception is java.lang.ClassNotFoundException: main.java.OutputHelper
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1141)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:758)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:422)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at mian.java.AppViaSpring.main(AppViaSpring.java:10)
Caused by: java.lang.ClassNotFoundException: main.java.OutputHelper
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
... 9 more
you forgot to add the JsonOutputGenerator bean for OutputHelper
try this:
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
<property name="outputGeneratorJson" ref="JsonOutputGenerator" />
</bean>
note you can also use context.getBean(OutputHelper.class), no casting will be required
edit:
on the further look at the problem. The setter you are using has two arguments which violates javaBean convention. There are few options.
1. You simply pass the map to the setter.
2. Create setter for each generator field.
3. You inject outputGeneratorCsv and outputGeneratorJson in the constructor - i would recommend that. In that case you would have to add constructor with two arguments (like your setter method) and modify the spring context xml to something like that:
<bean id="OutputHelper" class="main.java.OutputHelper">
<constructor-arg ref="outputGeneratorCsv"/>
<constructor-arg ref="outputGeneratorJson"/>
</bean>
here also some more info, why to use constructor injections:
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Setter injection versus constructor injection

Cannot use placeholder in static factory method creating a SpringLiquibase bean

Spring 3.1.0 with Liquibase 2.0.5 running on Glassfish 2.1.1 - From a long gone colleague I have inherited this applicationContext.xml which constructs a SpringLiquibase bean this way:
<bean id="liquibaseConfiguratore" factory-method="createLiquibaseBean" class="com.whatever.LiquibaseFactory">
<constructor-arg name="dataSource" ref="dataSourceConfiguratore"/>
<constructor-arg name="changeLog" value="classpath:liquibase/configuratore-db-changelog.xml"/>
<constructor-arg name="propFileName" value="/opt/whatever/ec_properties.properties"/>
</bean>
where LiquibaseFactory is a factory and the bean produced by the static method createLiquibaseBean has class
com.whatever.CustomLiquibase extends liquibase.integration.spring.SpringLiquibase
Now I need to parameterize the changeLog value, so that my bean declaration becomes:
<bean id="liquibaseConfiguratore" factory-method="createLiquibaseBean" class="com.whatever.LiquibaseFactory">
<constructor-arg name="dataSource" ref="dataSourceConfiguratore"/>
<constructor-arg name="changeLog" value="${tgo.liquibase.changelog.filename}"/>
<constructor-arg name="propFileName" value="/opt/whatever/ec_properties.properties"/>
</bean>
In order to set the correct value for the parameter, I browse the source of SpringLiquibase and I see that the String changeLog:
/**
* Sets a Spring Resource that is able to resolve to a file or classpath resource.
* An example might be <code>classpath:db-changelog.xml</code>.
*/
public void setChangeLog(String dataModel) { ... }
After reading this, I put the original string inside my properties file.
tgo.liquibase.changelog.filename=classpath:liquibase/configuratore-db-changelog.xml
and declare the props as:
<context:property-placeholder location="file:///opt/whatever/custom_properties.properties" />
But the bean fails during creation. Error message is:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibaseConfiguratore' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at
.....
Caused by: liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at liquibase.parser.ChangeLogParserFactory.getParser(ChangeLogParserFactory.java:61)
at liquibase.Liquibase.update(Liquibase.java:107)
at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:262)
Apparently the parser is found when there is a plain string in the XML. The moment I put a placeholder, the parser ain't there to be found. But it looks like the placeholder is resolved correctly, at least on screen...
I have tried some variations:
put file:/absolute/path/to/configuratore-db-changelog.xml in the property
put classpath*:liquibase/configuratore-db-changelog.xml in the property
put properties 'index=0,1,2' instead of 'name' inside tag constructor.arg
But the problem is still there.
How can I use a placeholder to specify the changeLog parameter?
HERE IS THE COMPLETE STACK TRACE:
[#|2014-06-25T09:19:54.860+0200|SEVERE|sun-appserver2.1|javax.enterprise.system.container.web|_ThreadID=12;_ThreadName=pool-1-thread-6;_RequestID=36e46602-c248-4e54-844e-6e5e11225bb8;|WebModule[/FastwebSme]PWC1275: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibaseConfiguratore' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4632)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5312)
at com.sun.enterprise.web.WebModule.start(WebModule.java:353)
at com.sun.enterprise.web.LifecycleStarter.doRun(LifecycleStarter.java:58)
at com.sun.appserv.management.util.misc.RunnableBase.runSync(RunnableBase.java:304)
at com.sun.appserv.management.util.misc.RunnableBase.run(RunnableBase.java:341)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at liquibase.parser.ChangeLogParserFactory.getParser(ChangeLogParserFactory.java:61)
at liquibase.Liquibase.update(Liquibase.java:107)
at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:262)
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 24 more
|#]
AND HERE IS LIQUIBASEFACTORY:
package com.whatever.util;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class LiquibaseFactory {
private static boolean enabled = !StringUtils.equals(
System.getProperty("liquibase.disable"), "true");
private static Logger log = Logger.getLogger(LiquibaseFactory.class);
public static CustomLiquibase createLiquibaseBean(DataSource dataSource,
String changeLog, String propFileName) {
log.info("dataSource is " + dataSource);
log.info("changeLog is " + changeLog);
log.info("propFileName is " + propFileName);
CustomLiquibase customLiquibase = null;
if (enabled) {
log.info("creating customLiquibase ENABLED");
customLiquibase = new CustomLiquibase(propFileName);
customLiquibase.setDataSource(dataSource);
customLiquibase.setChangeLog(changeLog);
} else {
log.warn("Liquibase has been disabled");
log.warn("\n\n" + StringUtils.repeat("*", 80));
log.warn(StringUtils.repeat("*", 80) + "\n\n");
}
return customLiquibase;
}
}
AND HERE IS CUSTOMLIQUIBASE:
package com.whatever.util;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import liquibase.integration.spring.SpringLiquibase;
import org.apache.log4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class CustomLiquibase extends SpringLiquibase {
private static final Logger LOGGER = Logger
.getLogger(CustomLiquibase.class);
public CustomLiquibase(String propertiesName) {
super();
LOGGER.info("propertiesName is " + propertiesName);
Resource resource = new FileSystemResource(new File(propertiesName));
try {
LOGGER.info("resource is " + resource);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
Map<String, String> ps = new HashMap<String, String>();
for (Object key : props.keySet()) {
Object value = props.get(key);
if (value != null) {
ps.put(key.toString(), value.toString());
}
}
this.setChangeLogParameters(ps);
} catch (IOException ex) {
LOGGER.error("", ex);
}
}
}

Spring batch late binding for stepExecutionContext not working

I am using Spring batch application and want to use late binding for stepExecutionContext. I am facing issues in resolving my error.
Following is my reader which has sql property using late binding:
<bean id="itemReader_S4_JPolicy" class="com.aegonusa.etl.readers.JDBCItemReader" scope="step">
<property name="jobParameters" ref="jobParameters" />
<property name="dataSource" ref="readDataSource" />
<property name="rowMapper">
<bean class="com.aegonusa.etl.readers.ResultSetRowMapper" scope="step" />
</property>
<property name="sql"
value="#{stepExecutionContext['readQuery']}"></property>
</bean>
I set this property ('readQuery') in following class:
public class StepListener implements StepExecutionListener
{
....
....
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate();
StepSynchronizationManager.getContext().setAttribute("readQuery", s);
.....
}
.....
}
Please note that I am able to do late binding using jobParameters.
But using stepExecutionContext, I get following exc. I tried lot of posts in forums but am unable to resolve it:
Throwable occurred: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lazyBindingProxy.itemReader_S4_JPolicy#sysinit' defined in class path resource [Load_InforceToStage.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:224)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:302)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.batch.core.scope.util.PlaceholderTargetSource.getTarget(PlaceholderTargetSource.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at $Proxy1.close(Unknown Source)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.item.ChunkMonitor.close(ChunkMonitor.java:99)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:297)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:255)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:49)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:349)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:574)
at com.ebsadm.lh.LHSHEDToStage.runJob(LHSHEDToStage.java:124)
at com.ebsadm.lh.LHSHEDToStage.main(LHSHEDToStage.java:111)
at com.ebdadm.lh.TestLHSHEDToStage.testInforceLoadToStage(TestLHSHEDToStage.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.batch.core.scope.util.PlaceholderTargetSource$1.convertIfNecessary(PlaceholderTargetSource.java:140)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1294)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
... 50 more
Kindly help.
I would expect a call to getExecutionContext on the StepExecution to give you the proper context.
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate()";
execution.getExecutionContext().putString("readQuery", s);
}
Your current solution is getting the StepContext. The StepContext is the object that is exposed and used for expression parsing, whereas the ExecutionContext associated with the StepExecution is the actual stepExecutionContext. ItemReaders and ItemWriters and such object also use the ExecutionContext to update the state (skipped items, commit count etc.).
Try any of the below :
Use promotionListener bean to promote the scope of variable from step to job.
Use bean instead of executionContext.

Tiles Config bean throws exception: TestNG+Spring 3+Tiles2

I'm trying to run a TestNG+Spring+JPA+Hibernate 'Hello World' test. The execution results in a NullPointerException, the tiles configurer bean fails.
The exception:
2011-08-20 18:12:18,547 [main] INFO org.springframework.web.servlet.view.tiles2.TilesConfigurer - TilesConfigurer: adding definitions [/WEB-INF/tiles/tiles.xml]
2011-08-20 18:12:18,552 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#68cb6b: defining beans [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#0,org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor#0,org.springframework.security.methodSecurityMetadataSourceAdvisor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,nethawalaDS,jspViewResolver,tilesViewResolver,tilesConfigurer,nethawalaEMF,transactionManager,jpaVendorAdapter,validator,auditLog,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,logoutHandlerBean,userDetailsService,customAuthenticationFailureHandlerBean,customAuthenticationSuccessHandlerBean,httpSessionEventListener,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.scheduling.annotation.internalAsyncAnnotationProcessor,org.springframework.scheduling.annotation.internalScheduledAnnotationProcessor,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,homeController,userSessionController,NHUserDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,nethawalaProperties,placeholderConfig]; root of factory hierarchy
2011-08-20 18:12:18,563 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#fdfc58] to prepare test instance [com.tigermindz.test.FacultyDaoTest#1afae45]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:133)
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)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:76)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:525)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:202)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:130)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:173)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.runWorkers(TestRunner.java:1147)
at org.testng.TestRunner.privateRun(TestRunner.java:749)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:317)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:312)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:274)
at org.testng.SuiteRunner.run(SuiteRunner.java:223)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1039)
at org.testng.TestNG.runSuitesLocally(TestNG.java:964)
at org.testng.TestNG.run(TestNG.java:900)
at org.testng.TestNG.privateMain(TestNG.java:1182)
at org.testng.TestNG.main(TestNG.java:1146)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [nethawala-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
... 28 more
Caused by: java.lang.NullPointerException
at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory$SpringWildcardServletTilesApplicationContext.(SpringTilesApplicationContextFactory.java:72)
at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory.createApplicationContext(SpringTilesApplicationContextFactory.java:55)
at org.springframework.web.servlet.view.tiles2.TilesConfigurer.afterPropertiesSet(TilesConfigurer.java:335)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 41 more
My applicationContext.xml, only showing the tiles config bean def:
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles.xml</value>
</list>
</property>
</bean>
Did a lot of googling, only thing found, people mentioned about cglib and/or asm jars in conflict with spring and hibernate dependencies. I don't think that is applicable here however my lib folder has the following jars, sorry not in order:
./tiles-template-2.2.2.jar
./spring-security-acl-3.0.5.RELEASE.jar
./org.springframework.context-3.0.5.RELEASE.jar
./hibernate-jpa-2.0-api-1.0.0.Final.jar
./tiles-api-2.2.2.jar
./validation-api-1.0.0.GA.jar
./org.springframework.web.servlet-3.0.5.RELEASE.jar
./hsqldb.jar
./spring-security-taglibs-3.0.5.RELEASE.jar
./commons-pool-1.5.6.jar
./aspectjrt-1.6.8.jar
./commons-beanutils-1.8.3.jar
./org.springframework.aop-3.0.5.RELEASE.jar
./spring-security-core-3.0.5.RELEASE.jar
./commons-collections-3.1.jar
./org.springframework.web-3.0.5.RELEASE.jar
./jstl-1.2.jar
./org.springframework.expression-3.0.5.RELEASE.jar
./dom4j-1.6.1.jar
./org.springframework.orm-3.0.5.RELEASE.jar
./log4j-1.2.16.jar
./org.springframework.beans-3.0.5.RELEASE.jar
./tiles-servlet-2.2.2.jar
./poi-3.7-20101029.jar
./spring-security-aspects-3.0.5.RELEASE.jar
./slf4j-api-1.6.1.jar
./aopalliance-1.0.jar
./slf4j-simple-1.6.1.jar
./hibernate3.jar
./slf4j-ext-1.6.1.jar
./spring-security-web-3.0.5.RELEASE.jar
./jta-1.1.jar
./asm-3.3.1.jar
./org.springframework.test-3.0.5.RELEASE.jar
./spring-security-config-3.0.5.RELEASE.jar
./org.springframework.core-3.0.5.RELEASE.jar
./org.springframework.asm-3.0.5.RELEASE.jar
./tiles-jsp-2.2.2.jar
./testng-6.0.1.jar
./commons-digester-2.1.jar
./commons-logging-1.1.1.jar
./org.springframework.transaction-3.0.5.RELEASE.jar
./javax.inject.jar
./commons-dbcp-1.4.jar
./slf4j-log4j12-1.6.1.jar
./hibernate-validator-4.1.0.Final.jar
./javassist-3.12.0.GA.jar
./tiles-core-2.2.2.jar
./aspectjweaver-1.6.8.jar
./org.springframework.jdbc-3.0.5.RELEASE.jar
./jackson-all-1.7.5.jar
./jstl-api-1.2.jar
./antlr-2.7.6.jar
./cglib-2.2.jar
The test class is as follows:
#ContextConfiguration(locations = { "classpath:test-servlet.xml" })
public class FacultyDaoTest extends AbstractTransactionalTestNGSpringContextTests {
private final XLogger logger = XLoggerFactory.getXLogger(FacultyDaoTest.class);
#Inject
FacultyDAO facultyDao;
#BeforeClass
public void setUp() {
logger.entry();
System.out.println("Inside setup");
}
#Test(groups = { "fast" })
#Rollback(value = false)
public void createFaculty() {
Faculty f = new Faculty();
f.setFirstName("John");
f.setLastName("Frost");
f.setCpsoNumber("23198");
f = facultyDao.makePersistent(f);
assert(f.getId() > 0);
}
#Test(groups = { "fast" })
public void aFastTest() {
logger.entry();
logger.info("Inside a Fast test");
}
#Test(groups = { "slow" })
public void aSlowTest() {
logger.entry();
logger.info("Inside a Slow test");
}
}
Any pointers will be greatly appreciated.
Your test load a web app specific configuration file, but your test environment does not provide the required files:
You need to separate the Web Application specific configuration from the one the works wihtout web application context.
Then use for the test the one that works without Web Application.
For you that mean: remove the Tiles Configuration for the test configuration. Because in the test the /WEB-INF/tiles/tiles.xml file is not available.

Resources