【问题标题】:Spring XML and java configuration togetherSpring XML 和 java 配置在一起
【发布时间】:2016-10-16 21:34:41
【问题描述】:

我有一个基于 XML 的 spring 配置项目,并且想要定义一些新的 bean,但是在基于 java 类的配置中。

如何实现这一点,以便我也可以在我的 XML 配置文件中引用 java 配置的 bean。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您可以将您的 xml 配置导入 java 配置,如下所示:

    @Configuration
    @ImportResource("classpath:pl/rav/springtest/resources/app.xml")
    public class AppConfig {
        @Bean(name="myMessageService")
        MessageService mockMessageService() {
            return new MessageServiceImpl();
        }
    }
    

    当你想从 xml 引用 bean 时,你只需指向它的名字:

    <property name="msgSrv">
        <ref bean="myMessageService"/>
    </property>
    

    然后根据你的java配置使用ApplicationContext。

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    

    当您开始使用 xml 配置时,您可能会对其他方式(将 java 配置导入 xml 配置)感兴趣,我认为这已解释 here

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 2013-10-24
      • 1970-01-01
      • 2023-03-21
      • 2016-04-01
      • 2017-06-21
      • 2016-10-24
      • 2012-10-19
      • 2013-10-22
      相关资源
      最近更新 更多