我正在尝试使用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"/>
我的回购链接是: https://bitbucket.org/rkc2015/gs-scheduling-tasks-complete
它是Spring启动的默认指南,用于执行计划任务。
我试图将xml文件中定义的Person POJO注入计划任务。
我目前收到此错误:
创建名称为&#39; scheduledTasks&#39;:注入自动装配的bean时出错 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 autowire字段:private hello.service.Person hello.service.ScheduledTasks.person;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有 为依赖项找到类型[hello.service.Person]的限定bean: 预计至少有1个豆有资格成为autowire候选人 这种依赖。依赖注释: {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}
有人可以帮忙吗?我是Spring的新手。
答案 0 :(得分:2)
您可以使用@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();
}
}
答案 1 :(得分:1)
如果这是通过spring bean你应该为你的bean定义使用@component注释,或者你应该使用application.xml来定义scheduledTasks bean并使用它的成员变量,这样两个bean都可以创建并且可以自动连接