我们的 Spring MVC Web 应用程序正在尝试遵循推荐的样式。它使用 AppContext( ContextLoaderListener
) 来存储 DAO 和服务。它使用 WebAppContext ( DispatcherServlet
) 来存储控制器。
DAO 对象同时进入AppContext和 WebAppContext。我不明白为什么。
AppContext 配置应该加载除控制器(以及将代码表加载到 ServletContext 中的类)之外的所有内容:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
@EnableTransactionManagement
@EnableScheduling
@ComponentScan(
basePackages = {"blah"},
excludeFilters = {
@Filter(type = FilterType.ANNOTATION, value = {Controller.class}),
@Filter(type = FilterType.ASSIGNABLE_TYPE, value = LoadOnStartup.class)
}
)
public class SpringRootConfiguration {
并且 Web 部件应该只加载控制器:
@Configuration
@EnableWebMvc
@ComponentScan(
basePackages = {"blah"},
includeFilters = @Filter(type = FilterType.ANNOTATION, classes={Controller.class})
)
public class SpringWebConfiguration extends WebMvcConfigurerAdapter {
(上面的类在一个单独的包中,它是'blah'的兄弟;没有进行自我扫描)。
当然,控制器引用 DAO 对象。在 Controller 中,那些 DAO 对象是@Autowired
.
我的期望是这些@Autowired
DAO 对象是从 AppContext 中检索的,而不是第二次创建,而是放置在 WebAppContext 中。但我认为它们是第二次被创造出来的。例如,此行在日志中出现两次,一次用于 AppContext,一次用于 WebAppContext:
Creating shared instance of singleton bean 'labelDao'
我错过了什么吗?
就好像根上下文和 Web 上下文之间的父子关系丢失了。