Spring-boot with Liquibase Overloading Property - spring-boot

I am using Spring boot and Liquibase.
Using this url as guidelines
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
In pom.xml, the below entry is present so that spring boot knows about liquibase.
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
and put the changelog file in resources folder.
db.changelog-master.xml
Now Spring boot first tring to find db.changelog-master.yaml in classpath and throwing the exception like this.
Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml
To Fix the Issue, I have added the bean like below in my class and tried to set changeLog proprty.
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class SampleDataJpaApplication {
#Autowired
LiquibaseProperties properties;
#Autowired
private DataSource dataSource;
#Bean
public SpringLiquibase liquibase() {
SpringLiquibase liquibase = new SpringLiquibase();
properties.setChangeLog("classpath:/db/changelog/db.changelog-master.xml");
liquibase.setChangeLog(this.properties.getChangeLog());
liquibase.setContexts(this.properties.getContexts());
liquibase.setDataSource(this.dataSource);
liquibase.setDefaultSchema(this.properties.getDefaultSchema());
liquibase.setDropFirst(this.properties.isDropFirst());
liquibase.setShouldRun(this.properties.isEnabled());
return liquibase;
}
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger("SampleDataJpaApplication");
SpringApplication springApplication = new SpringApplication();
springApplication.run(SampleDataJpaApplication.class, args);
}
}
but it is failing with the message.
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sampleDataJpaApplication': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field:
org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties
sample.data.jpa.SampleDataJpaApplication.properties; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties]
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)}
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties
sample.data.jpa.SampleDataJpaApplication.properties; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties]
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)}
Please provide the inputs here, why i am getting this exception or Is there any any other available way to override the same class so that i can change the changeLog property of liquibase properties.

I'm not entirely sure what the exact runtime path to your change log is, but why don't you just use the "liquibase.*" properties in application.properties? You should be able to leave out the Liquibase #Bean and let Boot do it for you.
If you prefer to add you own Liquibase #Bean then take the hint and make sure you define a LiquibaseProperties bean as well (e.g. by declaring #EnableConfigurationProperties(LiquibaseProperties.class)).

Related

NoBean found exception

**I am getting below error even though i have down the #autowired .please some one let me know why this issue happening its a ant build with spring config
utor.
2022-07-08 10:18:09,856 WARN org.springframework.context.support.
ClassPathXmlApplicationContext - Exception encountered during context initialization
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor':
Unsatisfied dependency expressed through field 'headerProcessor';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor': Unsatisfied dependency expressed
through field 'headerProcessor';
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException: No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]: expected at least 1 bean which qualifies as
autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
#Component
public class DelegateProcessor implements ItemProcessor<Object, Object>, InitializingBean {
#Autowired
#Qualifier("headerProcessor")
private ItemProcessor<FileHeader, FileHeader> headerProcessor;
#Autowired
#Qualifier("detailProcessor")
private ItemProcessor<FileDetail, FileDetail> detailProcessor;
#Autowired
#Qualifier("trailerProcessor")
private ItemProcessor<FileTrailer, FileTrailer> trailerProcessor;
#Component
public class HeaderProcessor implements ItemProcessor<Object, Object>{
#Autowired
private HeaderValidatorDao headerValidatorDao ;**
With a configuration class you could initialize your beans manually, specially if they need custom names.
#Configuration
public class MyCustomConfiguration {
#Bean(name ="headerProcessor")
public ItemProcessor<FileHeader, FileHeader> headerProcessorBean() {
ItemProcessor<FileHeader, FileHeader> myBean = new HeaderProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
#Bean(name ="detailProcessor")
public ItemProcessor<FileDetail, FileDetail> detailProcessorBean() {
ItemProcessor<FileDetail, FileDetail> myBean = new ItemProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
}
In this way these beans will be available for autowiring.

Why brave.Tracer can not be autowired in #Configuration class?

I'm upgrading spring-boot to 2.6.2 and spring-cloud to 2021.0.0, and after upgrading, the brave.Tracer was not able to autowired in a #Configuration class.
The Tracer is autowired as parameter with #Bean component.
I have tried solutions in this question but doesn't work.
here is the #Configuration class:
#Configuration
#ConditionalOnWebApplication
#AutoConfigureAfter(CommonsAutoConfig.class)
#EnableConfigurationProperties({CorsConfig.class, TracingConfiguration.class})
public class WebCommonsAutoConfig
{
......
#Bean(name = "httpRestRequestResponseLogger")
#RefreshScope
public FilterRegistrationBean httpRestRequestResponseLogger(
RequestResponseLogger requestResponseLogger,
HeaderAccessor headerAccessor,
Tracer tracer,
HeaderExtractor<HttpServletRequestLoggingWrapper> httpHeaderExtractor)
{
final HttpLogFilter httpLogFilter= new HttpLogFilter(requestResponseLogger,
headerAccessor, tracer, httpHeaderExtractor);
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(httpLogFilter);
registrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
registrationBean.setOrder(HttpLogFilter.ORDER);
return registrationBean;
}
....
}
With the following error log:
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'scopedTarget.httpRestRequestResponseLogger' defined in class
path resource [com/vzt/WebCommonsAutoConfig.class]: Unsatisfied dependency expressed
through method 'httpRestRequestResponseLogger' parameter 2;
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'brave.Tracer' available: expected at least 1 bean which
qualifies as autowire candidate. Dependency annotations: {}
So what shall I do to make the brave.Tracer autowired in this #Configuration class?
Most likely you need to add #AutoConfigureAfter(BraveAutoConfiguration.class). I understand that spring cloud sleuth is on the classpath?

spring retry unit test

I am using spring retry (http://docs.spring.io/spring-retry/docs/1.1.2.RELEASE/apidocs/) in a maven project and I have the following unit test
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class RetriableFileManagerTest {
#Autowired
#Qualifier("asset")
private AssetResource assetResource;
#Test
public void testRetry() throws URISyntaxException {
byte[] image = this.assetResource.fetchResource("name", "path");
verify(assetResource, times(3)).fetchResource("name", "path");
Assert.assertEquals("should be equal", "image", new String(image));
}
#Configuration
#EnableRetry
public static class SpringConfig {
#Bean(name = "asset")
public AssetResource assetResource() throws Exception {
AssetResource remoteService = mock(AssetResource.class);
when(remoteService.fetchResource(anyString(), anyString()))
.thenThrow(new RuntimeException("Remote Exception 1"))
.thenThrow(new RuntimeException("Remote Exception 2"))
.thenReturn("Completed".getBytes());
return remoteService;
}
}
}
However when I try to run the test it fails with
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ctp.cms.actions.handlers.repository.resources.AssetResource ctp.cms.actions.handlers.filemanager.RetriableFileManagerTest.assetResource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] 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), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] 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), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
Finally figured out the issue, I had to move the #Retryable annotation to the interface that AssetResource implements and autowire this interface type to the unit test.
Error message says
No qualifying bean of type
[ctp.cms.actions.handlers.repository.resources.AssetResource] found
for dependency
How is ctp.cms.actions.handlers.repository.resources.AssetResource declared?
Do you have #Component (#Service or similar annotation on it?) Is this package enabled for #ComponentScan ?

Is it possible to inject beans using an XML file in Spring?

I am trying to inject a bean into an application using an XML file. The main function has
try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring/application.xml")) {
context.registerShutdownHook();
app.setResourceLoader(context);
app.run(args);
} catch (final Exception ex) {
ex.printStackTrace();
}
I also have a Person POJO and is set in the xml file.
The xml defination is as follows:
<context:annotation-config/>
<bean id="person" class="hello.service.Person" p:name="Ben" p:age="25" />
<bean class="hello.HelloBeanPostProcessor"/>
The link to my repo is:
https://bitbucket.org/rkc2015/gs-scheduling-tasks-complete
It is the default guide from Spring boot that does a scheduled task.
I'm trying to inject the Person POJO defined in the xml file into a scheduled task.
I am currently getting this error:
Error creating bean with name 'scheduledTasks': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private hello.service.Person
hello.service.ScheduledTasks.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [hello.service.Person] 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)}
Can anyone please help? I am new to Spring.
You can use #ImportResource annotation to import xml configurations.
Documentation link
#SpringBootApplication
#EnableScheduling
#ImportResource("/spring/application.xml")
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}
If this is through spring bean you should have used #component annotation for you bean definition or else i application.xml you should have defined scheduledTasks bean also and with it member variable of person so that both beans are created and can be autowired.

struts2 + spring4 + mybatis3 if use #Transactional will be a mistake (Autowired(required=true))

I am using spring #Transactional to manage MySQL transactional.
But the way I add #Transactional is wrong.
#Service
//#Transactional(readOnly = true)
public class UserInfoService extends BaseService
#Autowired
private UserInfoAccessor userInfoAccessor;
//#Transactional
public void insert()
Map<String, String> map = new HashMap<>();
map.put("userName", "test");
userInfoAccessor.insert(map);
The error message I receive is:
Unable to instantiate Action, com.luotuo.xiaobao.action.IndexAction, defined for 'index' in namespace '/'Error creating bean with name 'com.luotuo.xiaobao.action.IndexAction': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.luotuo.xiaobao.service.UserInfoService com.luotuo.xiaobao.action.IndexAction.userInfoService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.luotuo.xiaobao.service.UserInfoService] 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)
You can download my project source here.
What is the correct way to set this up?

Resources