Reputation: 2230
I am trying to create a three-tier application with Spring, view
, logic
, data
, more or less. The view
depends on logic
which depends on data
.
How can I configure the Spring application in the view
project such that the dependency graph is able to be resolved?
For example:
In the view
layer:
@Controller
public class SomeView {
private final SomeService someService;
@Autowired
public SomeView(SomeService someService) {
this.someService = someService;
}
}
@Configuration
@EnableAutoConfiguration
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
In the logic
layer:
@Component
public class SomeService {
private final SomeData someData;
@Autowired
public SomeService(SomeData someData){
this.someData = someData;
}
}
In the data
layer:
@Component
public class SomeData {
}
This configuration is not able to boot because SomeService
can't resolve SomeData
because SomeData
is not scanned in the view
layers Application.java
Upvotes: 0
Views: 277
Reputation: 2294
when using @SpringBootApplication
Spring boot uses default values. If you take a look at the @SpringBootApplication definition you will see that :
Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.
The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes: [...]
That means :
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also, it means that when using default values for @ComponentScan
your packages sturctures shloud be as following :
If not following this structure you should tell to the @ComponentScan
the package where to find the components :
Example 1:
@Configuration
@EnableAutoConfiguration
@ComponentScan({"com.my.package.controller","com.my.package.domain"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Exemple 2 :
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = {SomeService.class, SomeData.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also, i advice you to check this guide on how to structuring your code in a Spring Boot Application.
Upvotes: 1