【问题标题】:Unable to import spring configuration class from project A into project B无法将项目A中的spring配置类导入项目B
【发布时间】:2019-04-14 04:50:22
【问题描述】:

我在 项目 A 中有以下课程,这是一个春季项目

@Configuration
class MyConfig{
   @Bean
   JmsTemplate jmsTemplate(){
       return  new JmsTemplate();
   }

   @Bean
   Test test(){
       return new Test();
   }
}

class Test{
   @Autowired
   JmsTemplate jmsTemplate;

   @PostConstuct
   public void init(){
      System.out.println("Test Constructed")
   }

   public void sendOrder(){
      System.out.println("Sending Order");
   }
}

我在 Project B

中有以下内容
@SpringBootApplication
class MySpringBootApp{

    public static void main(String[] args){
     final SpringApplication app = new SpringApplication(MainConfig.class);
     app.run(args);
    }
}

@Configuration
@Import(MyConfig.class)
class MainConfig implements CommandLineRunner{

   @Autowired 
   Test test;

   @Override
   public void run(String... strings) throws Exception{
      System.out.println("Placing order");
      test.sendOrder()
   } 
}

我已将项目 A 作为依赖项包含在项目 B 的 pom 中

来自 post 构造的 SYS OUT 或来自 Test 类的 sendOrder 均未打印。打印 MainConfig 的运行方法中的 SYS OUT .. 我不确定项目 A 中的 MyConfig 类是否包含在项目 B 中,没有编译或运行时错误。任何潜在客户表示赞赏

【问题讨论】:

  • 尝试使用 @Configuration 注释 MyConfig 类
  • 在你的主课中为什么你提到了 MainConfig.class。我认为它应该是 Myspringbootapp.class ,它是您的主引导类。还要检查你的包 A 的类测试,看不到它的组件类还是什么?
  • 将@Configuration 添加到MyConfig,但没有用。
  • @coder 我已经发表了我的评论,请您再次实施和测试。
  • 嗨 Gaurav,我添加了 MySpingBootApp 但仍然没有运气

标签: java spring-mvc spring-boot junit


【解决方案1】:

我认为问题出在主课上。 您忘记将 Spring Boot 应用程序本身(在本例中为 MySpringBootApp.class)包含到配置列表中。

应该是:

@SpringBootApplication
class MySpringBootApp{

 public static void main(String[] args){
  final SpringApplication app = new 
           SpringApplication(MySpringBootApp.class,MainConfig.class);
  app.run(args);
 }
}

【讨论】:

  • 您好,我将 MySpringBootApp 类添加到配置列表中,但仍然没有运气。不确定缺少什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多