【问题标题】:import annotation based spring project in xml based project在基于xml的项目中导入基于注解的spring项目
【发布时间】:2021-12-01 20:33:10
【问题描述】:

我有两个春季项目,

项目 A:使用 xml bean 配置构建。

Project B : 是使用 Annotations 构建的; A依赖于B;

如何在 A applicationContext 中加载 B bean。

我搜索但我发现如何使用注释加载 xml bean:@ImportResource

有没有办法做到这一点而不必创建两个应用程序上下文:

ApplicationContext applicationContextA = new ClassPathXmlApplicationContext("classpath:/applicationContextA.xml");

ApplicationContext applicationContextB = new AnnotationConfigApplicationContext(BConfiguration.class);

【问题讨论】:

    标签: java spring-framework-beans


    【解决方案1】:

    是的,您可以使用一个应用程序上下文

    您可以使用任一 ApplicationContext 实现结合使用 xml 和基于注释的配置。因此,您可以选择一个并使用以下方法之一来实现它。

    使用 ClassPathXmlApplicationContext

    使用 xml 时,您希望在 xml 文件中激活包扫描。

    在xml中:

    <context:component-scan base-package="com.yourdomain.packetstoscan"/>
    <bean id="myXmlConfiguredBean" class="com.yourdomain.MyXmlConfiguredBean"/>
    

    使用 AnnotationConfigApplicationContext

    使用注释时,您希望在配置类中包含带有注释的 xml 文件。

    在您的 Java 配置类中:

    @Configuration
    @ImportResource("classpath:yourContext.xml")
    public class MyAnnotationConfiguredBean { }
    

    Bean 创建顺序

    在测试这个时,我只注意到一个细微的差别,那就是 bean 创建顺序。但是,我认为这不会对您的申请产生任何影响。为了完整起见,我只是添加了这个。

    对于基于 Xml 的配置:

    INFO com.yourdomain.MyXmlApp - BEAN: myAnnotationConfiguredBean
    INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
    INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
    INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.event.internalEventListenerProcessor
    INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.event.internalEventListenerFactory
    INFO com.yourdomain.MyXmlApp - BEAN: myXmlConfiguredBean
    

    对于基于注释:

    INFO com.yourdomain.MyApp - BEAN: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
    INFO com.yourdomain.MyApp - BEAN: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
    INFO com.yourdomain.MyApp - BEAN: org.springframework.context.event.internalEventListenerProcessor
    INFO com.yourdomain.MyApp - BEAN: org.springframework.context.event.internalEventListenerFactory
    INFO com.yourdomain.MyApp - BEAN: myAnnotationConfiguredBean
    INFO com.yourdomain.MyApp - BEAN: myXmlConfiguredBean
    

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多