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

时间:2019-05-07 00:55:23

标签: spring-boot maven-module

我有两个SpringBoot模块。 commonsweb

commons模块中,我定义了一个bean: enter image description here

我可以在commons测试中得到这个bean enter image description here

但是不幸的是,我无法从其他模块中获取bean。 enter image description here

我弄错了吗?我想从我的commons模块中获得web模块中定义的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(){}
}

更新:它有效

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用SpringBootTest批注:

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

    @Test
    public void isEnvOk(){}
}

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

答案 2 :(得分:0)

为了扫描@Configuration bean,您需要为@SpringBootApplication指定基本软件包,然后添加以下行,它将起作用。

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