Search code examples
javaspringspring-bootgradlecomponent-scan

spring submodule bean not loading


I am having DemoService class in test-client module. Injecting this DemoService class from test-server module.

1st case(working):

Both test-server and test-client has root package as com.demo.test .

This case all the beans are loading.

2nd case: (working after component scan)

test-server has root package as com.demo.test .

test-client has root package as com.client.test

This case test-client beans are not loading. Expecting to ComponentScan.

3rd case: (not working even after component scan)

test-client module using one of the bean from test-server. this is not loading after @ComponentScan also.

How to overcome above scenarios?

Note: I have imported sub modules in build.gradle

implementation project(':test-client')


Solution

  • Yes, if test-client does not share the same base packages (defined by the package where your @SpringBootApplication class resides), then you will need to use ComponentScan in your test-server project:

    @ComponentScan(basePackages = "com.client.test")
    

    A good alternative would we to create your own Spring Boot starter project for the client code as described in section "Creating Your Own Auto-configuration" in the official Spring Boot documentation.