Error creating bean, Bean instantiation via factory method failed - spring-boot

am trying to configure elasticsearch in Spring boot but Bean instantiation is failing, Node Builder has been removed from elasticsearch api so am trying to use Settings.Builder but its not helping
below is the code:
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.demo.elastic.elasticdemo.repository")
public class ElasticConfiguration {
#SuppressWarnings("resource")
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws IOException {
File tempDir = File.createTempFile("temp-elastic", Long.toString(System.nanoTime()));
System.out.println("Temp directory: "+ tempDir.getAbsolutePath());
Settings.Builder settings = Settings.builder()
//http settings
.put("http.enable", "true")
.put("http.cor.enable", "true")
.put("http.cors.allow-origin", "https?:?/?/localhost(:[0-9]+)?/")
.put("http.port", "9200")
//transport settings
.put("transport.tcp.port", "9300")
.put("network.host", "localhost")
//node settings
.put("node.data", "true")
.put("node.master", "true")
//configuring index
.put("index.number_of_shards", "1")
.put("index.number_of_replicas", "2")
.put("index.refresh_interval", "10s")
.put("index.max_results_window", "100")
//configuring paths
.put("path.logs", new File (tempDir, "logs").getAbsolutePath())
.put("path.data", new File (tempDir, "data").getAbsolutePath())
.put("path.home", tempDir);
//.build();
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
return new ElasticsearchTemplate(client);
}
}
what am i doing wrong.??
error am getting:
2018-09-27 19:23:35.825 ERROR 57876 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loaders': Unsatisfied dependency expressed through field 'operations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [com/demo/elastic/elasticdemo/config/ElasticConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.core.ElasticsearchOperations]: Factory method 'elasticsearchTemplate' threw exception; nested exception is java.lang.NoClassDefFoundError: org/elasticsearch/transport/Netty3Plugin
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]

Related

Component Scan with both including package and excluding a class is not working SpringBoot

I am trying to scan a package com.training and want to exclude a specific class(SDIAuthorizerConfig.java) from scanning in componenet scan but it doesnt seems like working
package com.training.execution.tom.action;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import com.training.foundation.core.application.SDIServiceApplication;
import com.training.foundation.core.authorizer.config.SDIAuthorizerConfig;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
#SpringBootApplication
#ComponentScan(basePackages = "com.training",excludeFilters = #Filter(type= FilterType.ASSIGNABLE_TYPE, value=SDIAuthorizerConfig.class))
#EnableGlobalMethodSecurity(securedEnabled = true)
#EnableEurekaClient
#EnableAutoConfiguration
public class TOMActionServiceApplication extends SDIServiceApplication{
public static void main(String[] args) {
SpringApplication.run(TOMActionServiceApplication.class, args);
}
}
And getting this below error while starting the application in tomcat
Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'SDIAuthorizerFilter': Unsatisfied dependency expressed through field 'authorizer'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'SDILDAPAuthorizer': Unsatisfied dependency expressed through field 'populator';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SDIAuthorizerConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'sdi.ldap.url' in value "${sdi.ldap.url}"
the above property is being referenced inside SDIAuthorizerConfig class which I don't want my component scan to include so I have used the below but it still being scanned.
#ComponentScan(basePackages = "com.training",excludeFilters = #Filter(type= FilterType.ASSIGNABLE_TYPE, value=SDIAuthorizerConfig.class))

How to convert spring-boot-web-application to spring application

I'm following this spring-data-aerospike tutorial and setup the sample application and it is working fine.
Now I want to convert this spring boot application to spring application so I wrote the below code.
package com.aerospike.demo.simplespringbootaerospikedemo;
import com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.aerospike.core.AerospikeTemplate;
public class TestSpringConfig {
public static void main(String[] args) throws IOException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AerospikeConfiguration.class);
AerospikeTemplate template = ctx.getBean(AerospikeTemplate.class);
}
}
18:33:25.430 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aerospikeTemplate' defined in com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration: Unsatisfied dependency expressed through method 'aerospikeTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'aerospikeClient' defined in com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.aerospike.client.AerospikeClient]: Factory method 'aerospikeClient' threw exception; nested exception is com.aerospike.client.AerospikeException$Connection: Error -8: Failed to connect to host(s):
null 0 Error -8: java.net.ConnectException: Can't assign requested address (connect failed)
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:917)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:582)
org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
com.aerospike.demo.simplespringbootaerospikedemo.TestSpringConfig.main(TestSpringConfig.java:10)
So I did tweak the code liitle bit like below to set the properties into system -
import com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.aerospike.core.AerospikeTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.stream.Stream;
public class TestSpringConfig {
public static void main(String[] args) throws IOException {
System.out.println(ClassLoader.getSystemResourceAsStream("application.properties").available());
Properties props = new Properties();
InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("application.properties");
if (resourceAsStream != null) {
props.load(resourceAsStream);
}
if(props != null) {
System.setProperties(props);
}
try {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AerospikeConfiguration.class);
AerospikeTemplate template = ctx.getBean(AerospikeTemplate.class);
} catch (Exception e) {
StackTraceElement[] st = e.getStackTrace();
if(st != null) {
System.out.println("st.length = " + st.length);
}
Stream.of(st).forEach(System.out::println);
} catch (ExceptionInInitializerError e) {
System.out.println(e.getCause());
e.getCause().printStackTrace();
}
}
}
When I run the program with the changes above I get the below stack trace for e.getCause().printStackTrace() -
java.lang.NullPointerException
at ch.qos.logback.core.CoreConstants.<clinit>(CoreConstants.java:47)
at ch.qos.logback.classic.layout.TTLLLayout.doLayout(TTLLLayout.java:52)
at ch.qos.logback.classic.layout.TTLLLayout.doLayout(TTLLLayout.java:23)
at ch.qos.logback.core.encoder.LayoutWrappingEncoder.encode(LayoutWrappingEncoder.java:115)
at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:230)
at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:102)
at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:84)
at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51)
at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:270)
at ch.qos.logback.classic.Logger.callAppenders(Logger.java:257)
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:421)
at ch.qos.logback.classic.Logger.filterAndLog_0_Or3Plus(Logger.java:383)
at ch.qos.logback.classic.Logger.log(Logger.java:765)
at org.apache.commons.logging.LogAdapter$Slf4jLocationAwareLog.debug(LogAdapter.java:468)
at org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:628)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
at com.aerospike.demo.simplespringbootaerospikedemo.TestSpringConfig.main(TestSpringConfig.java:26)
I'm running out of the the available options. How to fix this error.
The code is on github here
I added line.separator=\n to the application.properties which fixed the issue

Can't start maven project. Autowire failed and creating DTO beans failed

Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grupaDTOToGrupa': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.service.GrupaService jwd.festival.support.GrupaDTOToGrupa.grupaService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaGrupaService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.repository.GrupaRepository jwd.festival.service.impl.JpaGrupaService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grupaRepository': Cannot create inner bean '(inner bean)#1cd201a8' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1cd201a8': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'igracDTOToIgrac': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.service.DrzavaService jwd.festival.support.IgracDTOToIgrac.drzavaService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaDrzavaService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.repository.DrzavaRepository jwd.festival.service.impl.JpaDrzavaService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'drzavaRepository': Cannot create inner bean '(inner bean)#42b64ab8' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#42b64ab8': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'utakmicaDTOToUtakmica': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.service.UtakmicaService jwd.festival.support.UtakmicaDTOToUtakmica.utakmicaService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaUtakmicaService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private jwd.festival.repository.UtakmicaRepository jwd.festival.service.impl.JpaUtakmicaService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'utakmicaRepository': Cannot create inner bean '(inner bean)#3f2ef586' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3f2ef586': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
***grupaDTOToGrupa:
package jwd.festival.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import jwd.festival.model.Grupa;
import jwd.festival.service.GrupaService;
import jwd.festival.web.dto.GrupaDTO;
#Component
public class GrupaDTOToGrupa implements Converter<GrupaDTO, Grupa> {
#Autowired
private GrupaService grupaService;
#Override
public Grupa convert(GrupaDTO source) {
Grupa grupa;
if(source.getId() == null) {
grupa = new Grupa();
}else {
grupa = grupaService.findOne(source.getId());
if(grupa == null) {
throw new IllegalStateException("Triied to convert non existing
object. GrupaDTOToGrupa");
}
}
grupa.setId(source.getId());
grupa.setNaziv(source.getNaziv());
return grupa;
}
public List<Grupa> convert(List<GrupaDTO> grupe) {
List<Grupa> ret = new ArrayList<>();
for(GrupaDTO g : grupe) {
ret.add(convert(g));
}
return ret;
}
}
***igracDTOToIgrac:
package jwd.festival.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import jwd.festival.model.Igrac;
import jwd.festival.service.DrzavaService;
import jwd.festival.service.IgracService;
import jwd.festival.web.dto.IgracDTO;
#Component
public class IgracDTOToIgrac implements Converter<IgracDTO, Igrac> {
#Autowired
private DrzavaService drzavaService;
#Autowired
private IgracService igracService;
#Override
public Igrac convert(IgracDTO source) {
Igrac igrac;
if(source.getId() == null) {
igrac = new Igrac();
igrac.setDrzava(drzavaService.findOne(source.getDrzavaId()));
} else {
igrac = igracService.findOne(source.getId());
}
igrac.setDrzava(source.getDrzavaId());
igrac.setId(source.getId());
igrac.setIme(source.getIme());
igrac.setPrezime(source.getPrezime());
return igrac;
}
public List<Igrac> convert(List<IgracDTO> igraci) {
List<Igrac> ret = new ArrayList<>();
for(IgracDTO i : igraci) {
ret.add(convert(i));
}
return ret;
}
}
***utakmicaDTOToUtakmica:
package jwd.festival.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import jwd.festival.model.Utakmica;
import jwd.festival.service.UtakmicaService;
import jwd.festival.web.dto.UtakmicaDTO;
#Component
public class UtakmicaDTOToUtakmica implements Converter<UtakmicaDTO,
Utakmica> {
#Autowired
private UtakmicaService utakmicaService;
#Override
public Utakmica convert(UtakmicaDTO source) {
Utakmica utakmica;
if(source.getId() == null) {
utakmica = new Utakmica();
}else {
utakmica = utakmicaService.findOne(source.getId());
if(utakmica == null) {
throw new IllegalStateException("Tried to modify non existant
utakmica. UtakmicaDTOToUtakmica");
}
}
utakmica.setId(source.getId());
utakmica.setDrzavaDomacin(source.getDrzavaDomacin());
utakmica.setDrzavaGost(source.getDrzavaGost());
utakmica.setRezultat(source.getRezultat());
return utakmica;
}
public List<Utakmica> convert(List<UtakmicaDTO> utakmice) {
List<Utakmica> ret = new ArrayList<>();
for(UtakmicaDTO u : utakmice) {
ret.add(convert(u));
}
return ret;
}
}

Why I am getting NoSuchBeanDefinitionException when I deploy my Spring application in Tomcat?

I am working with Spring and Spring Data JPA. When deploying my application in Tomcat I'm getting the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'myController': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private com.service.MyService com.controller.MyController.myService; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'MyService': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private com.repository.MyRepository com.service.MyService.myRepository; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
[com.repository.MyRepository] found for dependency: expected at least 1 bean which qualifies
as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
The following are my code:
MyController.java
package com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.domain.MyEntity;
import com.service.MyService;
#RestController
#RequestMapping(MyController.ROOT_RESOURCE_PATH)
public class MyController{
public static final String ROOT_RESOURCE_PATH = "/test";
#Autowired
private MyService myService;
#RequestMapping(value="/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<MyEntity> getAll() {
return myService.getAll();
}
}
MyService.java
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.domain.MyEntity;
import com.repository.MyRepository;
#Service(value = "MyService")
public class MyService {
#Autowired
private MyRepository myRepository;
public List<MyEntity> getAll() {
return myRepository.findAll();
}
}
MyRepository.java
package com.repository;
import java.util.List;
import org.springframework.data.repository.Repository;
import com.domain.MyEntity;
public interface MyRepository extends Repository<MyEntity, Long> {
public List<MyEntity> findAll();
}
}
MyApplication-context.xml
<jpa:repositories base-package="com.repository" />
<context:component-scan base-package="com.service" />
<context:component-scan base-package="com.controller" />
<context:annotation-config />
I'm not seeing your repository annotated. That might be the reason why Spring couldn't create a bean for MyRepository during component scan. Annotate it with #Repository

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

Resources