Spring boot fail to start while invoking external jar class which is xml based framework

Viewed 36

I am trying to call external jar methods from spring boot application. But the external jar is a xml based spring framework.

package com.ext.beans;

public class ExtBean{
    extMethod() {
     // some action
    };
}

in application-context.xml

<bean id="extBean" class="com.ext.beans.ExtBean" scope="prototype"/>

My Spring boot application:

@Configuration
@ComponentScan({"com.ext.beans"})
public class ParentConfig {

    @Bean("extBean")
    public ExtBean extBean() {
        return new ExtBean();
    }
}

@Service
public class ParentService {
    @Autowired
    @Qualifier("extBean")
    ExtBean extBean;
    
    public ParentServiceMethod() {
        //perform function with extBean method
        extBean.extMethod();
   }
}

spring boot application is fail start the application getting below error

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parentService': Unsatisfied dependency expressed through field 'extBean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'extBean' defined in class path resource [com/parent/config/ParentConfig.class]

FYI: i have added the external jar dependency in spring boot pom.xml

1 Answers

On the configuration class add

@ImportResource({"classpath*:application-context.xml"})

And remove @ComponentScan. This annotation scan the package for annotated beans like @Component\@Service. And you don’t have to declare the bean in the configuration class, it will be loaded by the @ImportResource

I wrote an example in spring-boot-starter-example\src\main\resources there is application-context.xml and in spring-boot-consumer\src\main\java\com\example\springbootconsumer\SpringBootConsumerApplication.java there is @ImportResource("classpath*:application-context.xml")

Related