1

I have two SpringBoot modules. commons and web.

In commons module, I define a bean: enter image description here

And I can get this bean In the commons test enter image description here

But unfortunately, I can not get the bean from anther module. enter image description here

Am I mistake something? I want to get the bean which defined in the commons module from my web module.

this is my 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(){}
}

Update: it works

Shuai Li
  • 2,426
  • 4
  • 24
  • 43

3 Answers3

0

You won't have access to beans defined in one Spring application from another. This is because each Spring application manages its beans separately and has an independent ApplicationContext (the interface that you use to get beans in your application).

Mustafa
  • 5,624
  • 3
  • 24
  • 40
0

Use SpringBootTest annotation:

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

    @Test
    public void isEnvOk(){}
}

Also, your YmlConfigTest should extend ModulesApplicationTest class.

0

In order to scan @Configuration bean, you need to specify base packages to @SpringBootApplication then add the following line and it will work.

@SpringBootApplication(scanBasePackages = {"com.github.fish56.modules.commons.config", 
                                           "com.github.fish56.modules"})
Jonathan JOhx
  • 5,784
  • 2
  • 17
  • 33