一个模块可以读取另一个模块的 bean 吗?

Can one module read another module's bean?

我有两个SpringBoot模块。 commonsweb.

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

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

但不幸的是,我无法从另一个模块中获取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(){}
}

更新:有效

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

使用SpringBootTest注释:

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

    @Test
    public void isEnvOk(){}
}

此外,您的 YmlConfigTest 应该扩展 ModulesApplicationTest class。

为了扫描@Configuration bean,你需要指定基础包到@SpringBootApplication然后添加下面一行就可以了。

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