【问题标题】:how to load spring bean from imported maven dependency without importing the context.xml如何在不导入 context.xml 的情况下从导入的 maven 依赖项加载 spring bean
【发布时间】:2016-04-07 20:09:38
【问题描述】:

我想在启动时加载 Spring Bean,它们存在于导入的 maven 依赖项中。有没有办法在不从注入的依赖 jar 中实际导入 context.xml 的情况下做到这一点?

我尝试了@EnableAutoConfiguration,但没有成功。

【问题讨论】:

    标签: spring-integration


    【解决方案1】:

    嗯嗯。没有选择。如果不告诉它这样做,Spring 应用程序上下文中不会出现任何内容。

    如果你的依赖只有context.xml,那么除非@Import,否则没什么神奇的。

    @EnableAutoConfiguration 仅适用于org.springframework.boot.autoconfigure.EnableAutoConfiguration 注册的用户。

    spring-boot-autoconfigure/META-INFO 中查看spring.factories

    正确:阅读更多 Spring Boot 文档。

    所以,如果你不想@Import,你可以用@Import写一些@Configuration(例如MyAutoConfiguration)并将spring.factories添加到你的任何jar中,内容如下:

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.my.proj.autoconfigure.MyAutoConfiguration
    

    【讨论】:

    • 我在 maven-project A 中有一个 @Configuration bean,我在其中定义了 xxx bean。
    • ???和?我指出的其他一切怎么样?抱歉,但您的评论毫无用处,而且比帮助更嘈杂。
    • 我已经在 maven-project A 中有一个 @Configuration 类,我在其中定义了 xxx bean。现在我将 maven-project A 作为 maven 依赖项包含在另一个 maven-project B 中。有没有一种方法可以引用 maven-project A 的 XXX bean 而无需在 web.xml 中显式导入 @Configuration
    • 我不知道你为什么也认为我的答案与这条评论无关......或者你使用@Import 或在spring.factories 上这样做,如果你基于弹簧靴。仅此而已。
    • 我添加了 spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration 键值对,但仍然抛出错误 NoSuchBeanDefinitionException。
    【解决方案2】:

    您可以在应用程序中创建一个 bean 并扩展要加载的 bean。

    示例(我用它来外部化rabbitmq绑定定义):

    外部:

    package com.bpedroso.rabbitmq.beans;
    
    import org.springframework.amqp.core.Binding;
    import org.springframework.amqp.core.BindingBuilder;
    import org.springframework.amqp.core.DirectExchange;
    import org.springframework.amqp.core.FanoutExchange;
    import org.springframework.amqp.core.Queue;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class CustomerMQBinding {
    
    @Bean
    public Queue myQueue() { ... }
    
    @Bean
    public Queue myDlq() { ... }
    
    @Bean
    public DirectExchange myExchange() { ... }
    
    @Bean
    FanoutExchange myDlx() { ... }
    
    /*
     * Bindings
     */
    @Bean
    Binding bindingMyrQueue(final Queue myQueue, final DirectExchange myExchange) { ... }
    
    @Bean
    Binding bindingMyDlq(final Queue myDlq, final FanoutExchange myDlx) { ... }
    }
    

    当前项目:

    import org.springframework.context.annotation.Configuration;
    import com.bpedroso.rabbitmq.beans.CustomerMQBinding;;
    
    @Configuration
    public class MyCustomerBindingMQBeans extends CustomerMQBinding {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2016-12-18
      • 2019-10-03
      • 2012-07-12
      • 1970-01-01
      相关资源
      最近更新 更多