@RestController not found if main class is not in top-level package

I have a class Resource

annotated with @RestController

, but it is only used if the main class App

annotated with @SpringBootApplication

is in the top-level package.

Works:

com
 +- test
     +- project
         +- App.java
         |
         +- resources
         |   +- Resource.java

      

Does not work:

com
 +- test
     +- project
         +- app
         |   +- App.java
         |
         +- resources
         |   +- Resource.java

      

+3


source to share


2 answers


I am assuming you are using annotation @SpringBootApplication

. You should be aware that this is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan.

From the documentation

ComponentScan configures component scan directives for use with @Configuration classes. Provides parallel support to the Spring XML element.

One of basePackageClasses (), basePackages () or its alias () can be used to define specific packages to scan. If certain packages are not defined. Scanning will happen from the package of the class with this annotation.



You went with the default settings, so your scan happens in the annotated class package.

You can either move it the way you want or specify basePackages in @ComponentScan.

+3


source


In the documentation, you can find the main class above all other classes to avoid usingbasePackage



We usually recommend that you find the main class of your application in the root package above the other classes. Annotation is @EnableAutoConfiguration

often placed in your main class and implicitly defines a base "search package" for certain elements.
...
Using the root package also allows you to use annotation @ComponentScan

without specifying an attribute basePackage

. You can also use annotation @SpringBootApplication

if your main class is in the root package.

+1


source







All Articles