【问题标题】:Can one module read another module's bean?一个模块可以读取另一个模块的bean吗?
【发布时间】:2019-05-07 00:55:22
【问题描述】:

我有两个 SpringBoot 模块。 commonsweb

commons 模块中,我定义了一个bean:

我可以在commons 测试中得到这个bean

但不幸的是,我无法从 anther 模块获取 bean。

我是不是搞错了什么?我想从我的web 模块中获取commons 模块中定义的bean。

这是我的 ModulesApplication.java

package com.github.fish56.modules;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ModulesApplication {
    public static void main(String[] args) {
        SpringApplication.run(ModulesApplication.class, args);
    }
}

ModulesApplicatonTest.java

package com.github.fish56.modules;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootApplication
public class ModulesApplicationTest {
    @Test
    public void isEnvOk(){}
}

更新:可以了

【问题讨论】:

  • 能否添加ModulesApplication类代码?
  • @JonathanJohx 是的,我补充了一些。

标签: spring-boot maven-module


【解决方案1】:

使用SpringBootTest注解:

@SpringBootTest(
  classes = {CommonsApplication.class, ModulesApplication.class})
@RunWith(SpringRunner.class)
public class ModulesApplicationTest {
    @Autowired
    private YmlConfig ymlConfig;

    @Test
    public void isEnvOk(){}
}

另外,您的 YmlConfigTest 应该扩展 ModulesApplicationTest 类。

【讨论】:

  • @bitfishxyz 你能在 Github 上发布你的项目吗?
  • @bitfishxyz 如果对您有帮助,您可以接受我的回答。
【解决方案2】:

您将无法从另一个 Spring 应用程序访问定义在一个 Spring 应用程序中的 bean。这是因为每个 Spring 应用程序都单独管理其 bean 并具有独立的 ApplicationContext(用于在应用程序中获取 bean 的接口)。

【讨论】:

    【解决方案3】:

    为了扫描@Configuration bean,您需要将基础包指定为@SpringBootApplication,然后添加以下行即可。

    @SpringBootApplication(scanBasePackages = {"com.github.fish56.modules.commons.config", 
                                               "com.github.fish56.modules"})
    

    【讨论】:

    • 嗨,您是否也为 ModulesApplication 和 ModulesApplicationTest 添加了这个?
    猜你喜欢
    • 2018-10-01
    • 2021-07-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-08-28
    • 2019-06-12
    相关资源
    最近更新 更多