2016-01-13 54 views
0

我正在嘗試使用XML文件將一個bean注入到應用程序中。主要功能有是否可以在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"/> 

鏈接到我的回購協議是: https://bitbucket.org/rkc2015/gs-scheduling-tasks-complete

正是從春天開機,做了計劃任務的默認導向。

我正在嘗試將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很陌生。

+0

,解答題你的問題: 「是的,是的,它是。」 – kryger

回答

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

感謝您的解決方案併發布了doco鏈接。隊友的歡呼聲! – rkc88

1

如果這是通過spring bean,你應該爲你的bean定義使用了@component註解,否則我在application.xml中你也應該定義了scheduledTasks bean,並且使用它的成員變量來創建這兩個bean,並且可以自動裝配。

相關問題