Juc
Juc

Reputation: 227

Why does Spring Autowire fail when I move @SpringBootApplication?

I'm completely new to Spring/Spring Boot so I need some help. I didn't notice any documentation that indicated that the @SpringBootApplication or @ComponentScan had to be in a particular spot:

Working folder structures

Working folder structure

Working folder structure 2

Not working

Not working folder structure

Upvotes: 1

Views: 208

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48133

I suppose your Application class is a typical Spring Boot Application like following:

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

SpringBootApplication is just a composed annotation of:

// Others
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication { .. }

That ComponentScan with no explicit base package, would use the package of Application class as its base package for scanning. So, when you put this class in your root package, any annotated class in root package and under it would be scanned by the component scanner and your app would successfully work.

But when you move your Application into app package, that very same component scanner wouldn't scan those beans in hello package and Spring would fail to wire some beans together.

Spring Boot does not require any specific code layout to work, however, there are some best practices that help. You can read about those best practices in Spring Boot Documentation.

Upvotes: 3

Related Questions