Search code examples
spring-bootmaven-module

Can one module read another module's bean?


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


Solution

  • 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.