Search code examples
springspring-bootjavabeans

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.


Solution

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