是否可以使用 Spring 中的 XML 文件注入 bean?

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

我正在尝试使用 XML 文件将 bean 注入到应用程序中。主要功能有

try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring/application.xml")) {
            context.registerShutdownHook();
            app.setResourceLoader(context);
            app.run(args);
        } catch (final Exception ex) {
            ex.printStackTrace();
        }

我还有一个 Person POJO 并在 xml 文件中设置。

xml定义如下:

<context:annotation-config/>
    <bean id="person" class="hello.service.Person" p:name="Ben" p:age="25" />
    <bean class="hello.HelloBeanPostProcessor"/>

我的回购 link 是: https://bitbucket.org/rkc2015/gs-scheduling-tasks-complete

它是 Spring 引导执行计划任务的默认指南。

我正在尝试将 xml 文件中定义的 Person POJO 注入到计划任务中。

我目前收到此错误:

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

有人可以帮忙吗?我是 Spring.

的新手

如果这是通过 spring bean 你应该为你的 bean 定义使用 @component 注释,否则我 application.xml 你应该已经定义了 scheduledTasks bean 和它的成员变量 person 这样两个 bean 都已创建并且可以自动装配。

您可以使用@ImportResource 注解来导入xml 配置。

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