0

我们的 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.

我的期望是这些@AutowiredDAO 对象是从 AppContext 中检索的,而不是第二次创建,而是放置在 WebAppContext 中。但我认为它们是第二次被创造出来的。例如,此行在日志中出现两次,一次用于 AppContext,一次用于 WebAppContext:

Creating shared instance of singleton bean 'labelDao'

我错过了什么吗?

就好像根上下文和 Web 上下文之间的父子关系丢失了。

4

1 回答 1

2

使用include不自动意味着禁用默认值的过滤器时。默认情况下,@ComponentScan将检测所有@Component类,无论 yu 指定什么include。因此,如果您想明确控制要扫描的注释,您首先必须禁用默认值。To do 设置to的useDefaultFilters属性。@ComponentScanfalse

@ComponentScan(
 basePackages = {"blah"},
 useDefaultFilters=false,
 includeFilters = @Filter(type = FilterType.ANNOTATION, classes={Controller.class})
)

现在它只会检测@Controller带注释的bean。

于 2016-02-25T07:04:24.140 回答