我见过在@Configuration中定义@Configuration的AutoConfiguration类,这些类都是static。为什么它们应该是静态的?这是一种更好的方式吗。
在@Component类中定义的@Configuration与独立的@Configuration类有什么不同?
发布于 2016-04-11 20:03:37
看看WebMvcAutoConfigurationAdapter在WebMvcAutoConfiguration的source code中的定义,就能找到答案:
// Defined as a nested config to ensure WebMvcConfigurerAdapter is not read when not
// on the classpath
@Configuration
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
...
}自动配置类被定义为嵌套的静态类,以防止Spring的组件扫描在未使用适当的注释时自动获取它们。因此,一个好的经验法则是,如果您希望每次都使用配置类,则将其定义为独立类;如果希望将其从类路径扫描中分离出来,则将其定义为嵌套静态类。
https://stackoverflow.com/questions/36547767
复制相似问题