I've just started a new spring project, and this time I want to do things "right". In the last project I had issues with multiple registering of certain classes because of multiple @ComponentScan
annotations. (i.e. all service classes got registered twice)
Basically I'm using the following layout:
WebAppInitializer
:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
RootConfig
:
@Configuration
@ComponentScan
public class RootConfig {
/* ... */
}
WebMvcConfig
:
@EnableWebMvc
@ComponentScan
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/* ... */
}
DatabaseConfig
:
@Configuration
@EnableJpaRepositories("my.base.class.path")
public class DataConfig {
/* ... */
}
The first basic question is: Which class should scan for which classes/annotations?
Should only the WebMvcConfig
scan for @Controller
classes? Which one should scan for @Service
and for @Configuration
and for @Component
?
The second question is: Or should I simply use packages to narrow down the scan path?
Example:
rootpackage
rootpackage.config.RootConfig
rootpackage.config.DatabaseConfig
rootpackage.mvc.WebMvcConfig
and then place all @Controller
classes under rootpackage.mvc.*
?
The third question is: Is it more common to let RootConfig
scan for DatabaseConfig
? Or should I place DatabaseConfig
inside the getRootConfigClasses
method of WebAppInitializer
class?
The last question is: In a multi module project: How do you organize those things?
Example: If I chose the way I described in question two, I could say, that every module of the app will in fact consist of a few different modules. Let's say, I want to create a module X
which will have a @Service
class and a few @Controller
classes, I could put them in them in different packages. Like this:
Maven Module X Service
rootpackage.services.x.XService
rootpackage.services.x.XServiceImpl
Maven Module X Controller
rootpackage.mvc.controller.x.X1Controller
rootpackage.mvc.controller.x.X2Controller
rootpackage.mvc.controller.x.X3Controller
And if you'd suggest this way, then: Where to place models and repositories (for accessing the database)? Should I create a new module for each of those?
Thanks in advance!