SpringBoot ComponentScan issue with multi-module project

ghz 1years ago ⋅ 2870 views

Question

I have a myapp parent pom type maven project with myapp-core and myapp-web modules. myapp-core module is added as dependency to myapp-web.

All the classes in myapp-core module reside in root package com.myapp.core and all classes in myapp-web module reside in root package com.myapp.web

The main Application.java is also in com.myapp.web package. As my core module root package is different I am including common base package "com.myapp" for ComponentScan as follows:

@Configuration
@ComponentScan(basePackages="com.myapp")
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }   
}

Now the surprising thing is if I run this app using Run As - > Spring Boot App it is working fine. But if I run it as Run As - > Java Application it is failing with error saying it can't found beans defined in myapp-core module.

If I move my Application.java to com.myapp package it is working fine. It should work even if i run it as Java Application also, right?


Answer

After enabling debug log level for spring and going through extensive logs I found that scanning for various components like JPA Repositories, JPA Entities etc are depending on the Application.java's package name.

If the JPA Repositories or Entities are not in sub packages of Application.java's package then we need to specify them explicitly as follows:

@Configuration
@ComponentScan(basePackages="com.sivalabs.jcart")
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages="com.sivalabs.jcart")
@EntityScan(basePackages="com.sivalabs.jcart")
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

With the above additional @EnableJpaRepositories, @EntityScan I am able to run it using Run As - > Java Application.

But still not sure how it is working fine when Run As - > Spring Boot App!!

Anyway I think it is better to move my Application.java to com.myapp package rather than fighting with SpringBoot!