Cannot use placeholder in static factory method creating a SpringLiquibase bean - spring

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

Related

: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

I am facing the below error while executing the below code.
I have my class names as below.
class Dad.java
package TestingDependecy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom) {
this.mom = mom;
}
public Dad (Child child) {
this.child = child;
}
public void name() throws IOException {
System.out.println("please enter a name ..");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
System.out.println("Please confirm your deatails below");
System.out.println("Your name is "+ name);
}
public void whichWork() {
mom.cooking();
}
public void mainWork() {
System.out.println("Don't distrub me Please...!!");
child.main();
}
}
class Mom.java
package TestingDependecy;
public class Mom {
public void cooking() {
System.out.println("I am cooking ");
System.out.println(" what else i can do ?");
}
}
Class Child
package TestingDependecy;
public class Child {
public void main() {
System.out.println("This is from child class");
}
}
Class Family.java
package TestingDependecy;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import TestingDependecy.Dad;
public class Family {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Dad d = context.getBean("dad", Dad.class);
d.mainWork();
System.out.println();
d.whichWork();
context.close();
}
}
Finally my ApplicationContext.xml file as below
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">
<!-- This is for family Package -->
<bean id = "mom"
class="TestingDependecy.Mom">
</bean>
<bean id = "child"
class="TestingDependecy.Child">
</bean>
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
I'm getting the below while executing the code.
Please find the error below.
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1a1cd57: startup date [Fri May 04 08:45:01 IST 2018]; root of context hierarchy
May 04, 2018 8:45:02 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ApplicationContext.xml]
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at TestingDependecy.Family.main(Family.java:13)
Please help me on this, what is the mistake I did here?
Regards,
Saikiran.
in ApplicationContext.xml you've passed two arguments to the constructor of dad bean :
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
So you have to define a two-argument constructor in Dad class like this:
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom, Child child) {
this.mom = mom;
this.child = child;
}
...
}
NOTE
all keep one constructor and corresponding bean constructor class
<bean id="e" class="com.test.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg> <ref bean="a1"/> </constructor-arg >
<constructor-arg> <ref bean="company"/> </constructor-arg>
</bean>
public Employee(int idx, String name, Address address, Company company) {
this.idx=idx;
this.name=name;
this.address=address;
this.company=company;
}

Spring:Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]

I am new new to spring programming.While executing a program for fetching some records from mysql database i am getting these errors:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'jtemplate' while setting bean property 'jdbcTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jtemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
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:222)
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 Test.main(Test.java:15)
I have three files in my project.
1.EmpDAO.java:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class EmpDAO {
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudents(){
return (List<Student>) template.query("select * from test",new ResultSetExtractor(){
#Override
public List<Student> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student e=new Student();
e.setName(rs.getString(1));
e.setRoll(rs.getString(2));
list.add(e);
}
return list;
}
});
}
}
2.Student.java:
public class Student {
private String name;
private String roll;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void display(){
System.out.println("Name: "+name+" Roll="+roll);
}
}
3.applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmpDAO">
<property name="jdbcTemplate" ref="jtemplate"></property>
</bean>
</beans>
4.Test.java(for execution):
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmpDAO dao=(EmpDAO)factory.getBean("edao");
List<Student> list=dao.getAllStudents();
for(Student e:list)
System.out.println(e);
}
}
The jars that i included in reference library:
These are the jars i included
Kindly help me in this regards.A prevalentines day thank you is in advance.
The relevant part of your errormessage is:
java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
You can download that jar from here: 5.1.38, or look for different versions on the central nexus repository.
Note: you would be much better of employing some dependency management system, rather than doing this manually. I suggest taking a look at Maven.

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

ConnectionPooling Configuration while using Spring jdbcTemplate

I am developing an application that needs to call a DB2 function on the mainframe to get an id.
In my spring application context, I have defined my jdbc template to query DB2 on zOS thusly:
<bean id="jdbcTemplateDB2"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceDB2"/>
</bean>
I then define the datasource as follows:
<bean id="dataSourceDB2"
class="com.ibm.db2.jcc.DB2DataSource">
<property name="serverName" value="hostname" />
<property name="portNumber" value="portno"/>
<property name="databaseName" value="dbname"/>
<property name="driverType" value="4"/>
<property name="user" value="userid"/>
<property name="password" value="password"/>
</bean>
The above works.
However, looking inside the ibm's db2jcc.jar files, I see a class for datasource WITH connection pooling - com.ibm.db2.jcc.DB2ConnectionPoolDataSource. So I tried to use that instead of the one above - like so :
<bean id="dataSourceDB2"
class="com.ibm.db2.jcc.DB2ConnectionPoolDataSource">
<property name="serverName" value="hostname" />
<property name="portNumber" value="portno"/>
<property name="databaseName" value="dbname"/>
<property name="driverType" value="4"/>
<property name="user" value="userid"/>
<property name="password" value="password"/>
</bean>
However, using the DB2ConnectionPoolDataSource gives me the following error.
Cannot convert value of type [com.ibm.db2.jcc.DB2ConnectionPoolDataSource] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
The complete stackTrace is below
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'classUniqueIdDaoImpl_v2': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplateDB2' defined in class path resource [META-INF/spring/applicationContext-db2.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.ibm.db2.jcc.DB2ConnectionPoolDataSource' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.ibm.db2.jcc.DB2ConnectionPoolDataSource] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
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:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.slma.euclid.core.dao.MainDB2.main(MainDB2.java:18)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplateDB2' defined in class path resource [META-INF/spring/applicationContext-db2.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.ibm.db2.jcc.DB2ConnectionPoolDataSource' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.ibm.db2.jcc.DB2ConnectionPoolDataSource] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
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.findAutowireCandidates(DefaultListableBeanFactory.java:876)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:439)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:417)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:304)
... 13 more
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.ibm.db2.jcc.DB2ConnectionPoolDataSource' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.ibm.db2.jcc.DB2ConnectionPoolDataSource] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:485)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:516)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1406)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1365)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 27 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [com.ibm.db2.jcc.DB2ConnectionPoolDataSource] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
... 33 more
What am I doing wrong? What is the correct way to use a connection pooled datasource while instantiating the Spring JdbcTemplate?
Any help is appreciated.
-SGB
Have you read this one: http://forum.springsource.org/showthread.php?66142-How-to-use-javax-sql-datasource-with-a-ConnectionPoolDataSource
It says com.ibm.db2.jcc.DB2DataSource is already a connection pool if used correctly.
An annotation based approach with Spring and DB2ConnectionPoolDataSource:
application.properties
spring.datasource.url=jdbc:db2://DBHOST:50000/DB:currentSchema=MYSCHEMA;currentFunctionPath=MYSCHEMA;\
clientProgramName=APPNAME-MYSCHEMA;\
progressiveStreaming=2;retrieveMessagesFromServerOnGetMessage=true;fullyMaterializeLobData=true;\
clientApplcompat=V12R1M500;jdbcCollection=NULLIDV12R1M500;currentPackageSet=NULLIDV12R1M500;
spring.datasource.username=USER
spring.datasource.password=PWD
ApplicationConfig.java
#Configuration
#PropertySource("classpath:application.properties")
public class ApplicationConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class);
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean
public DB2ConnectionPoolDataSource dataSource() {
LOGGER.info("DATASOURCE: " + url);
DB2ConnectionPoolDataSource ds = new DB2ConnectionPoolDataSource();
ds.setDriverType(4);
Properties hostPortDb = splitUrlHostPortDb(url);
ds.setServerName(hostPortDb.getProperty("server"));
ds.setPortNumber(Integer.parseInt(hostPortDb.getProperty("port")));
ds.setDatabaseName(hostPortDb.getProperty("db"));
Properties paramValuePairs = splitUrlParamValuePairs(url);
setParamValuePairs(ds, paramValuePairs);
ds.setUser(username);
ds.setPassword(password);
return ds;
}
private Properties splitUrlHostPortDb(String url) {
Properties properties = new Properties();
int hostIndex = url.indexOf("//");
int lastColonIndex = url.lastIndexOf(":");
String hostPortDb = url.substring(hostIndex, lastColonIndex);
URI uri = URI.create(hostPortDb);
properties.put("server", uri.getHost());
properties.put("port", uri.getPort() + "");
properties.put("db", uri.getPath().substring(1));
return properties;
}
private Properties splitUrlParamValuePairs(String url) {
Properties properties = new Properties();
int lastColonIndex = url.lastIndexOf(":");
String paramValues = url.substring(lastColonIndex + 1);
paramValues = paramValues.replaceAll(";", "\n");
try {
properties.load(new StringReader(paramValues));
} catch (IOException ex) {
String msg = "DATASOURCE: " + paramValues;
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
}
return properties;
}
private void setParamValuePairs(DB2ConnectionPoolDataSource ds, Properties properties) {
for (Object key : properties.keySet()) {
String value = (String) properties.get(key);
setter(ds, (String) key, value);
}
}
private void setter(DB2ConnectionPoolDataSource ds, String key, String value) {
boolean invoked = false;
String setterName = "set" + StringUtils.capitalize(key);
try {
Method[] methods = DB2ConnectionPoolDataSource.class.getMethods();
for (Method method : methods) {
if (method.getName().equals(setterName)) {
method.setAccessible(true);
if (method.getParameterTypes()[0] == String.class) {
method.invoke(ds, value);
invoked = true;
} else if (method.getParameterTypes()[0] == short.class) {
method.invoke(ds, Short.parseShort(value));
invoked = true;
} else if (method.getParameterTypes()[0] == int.class) {
method.invoke(ds, Integer.parseInt(value));
invoked = true;
} else if (method.getParameterTypes()[0] == long.class) {
method.invoke(ds, Long.parseLong(value));
invoked = true;
} else if (method.getParameterTypes()[0] == boolean.class) {
method.invoke(ds, Boolean.parseBoolean(value));
invoked = true;
}
LOGGER.info("DATASOURCE: " + method.getParameterTypes()[0] + " " + method + "=" + value);
}
}
} catch (Exception ex) {
String msg = "DATASOURCE: Assignment " + setterName + "=" + value + " failure - check type of argument.";
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
}
if (!invoked) {
String msg = "DATASOURCE: Method " + setterName + " not found - typo in DB URL.";
LOGGER.error(msg);
throw new RuntimeException(msg);
}
}
}
Use the DataSource in a Spring Bean:
#Autowired
private DB2ConnectionPoolDataSource dataSource;
And:
connection = dataSource.getPooledConnection().getConnection();

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

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.

Resources