为什么我们在 applicationContext.xml 和 dispatcher-servlet 中分别声明 </context:component-scan>.xml



为什么有时我们单独声明context:component-scan

在 applicationContext 中.xml我们声明如下:

<ctx:component-scan base-package="com.*"> <ctx:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </ctx:component-scan>

在 dispatcher-servlet 中.xml我们声明如下:

<context:component-scan base-package="com.*.*.controller.*" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>

我们为什么不直接在 applicationContext 中声明.xml如下所示:

<context:component-scan base-package="com.*"/>

然后将检测所有注释@Controller,@Service,@Repository的组件

这种分离意味着允许定义多个调度程序 servlet 并重用核心业务组件。

通常,您将在application-context.xml中定义存储库和服务之类的内容,并绑定到整个servlet上下文(通过使用ContextLoaderListener),并定义一个或多个调度程序servlet,每个Servlet都有自己的(子)上下文(由控制器和mvc实用程序组件组成),这些上下文将重用父上下文中的相同bean。

我会说,即使你只有一个调度程序,这种分离也是有意义的,因为它迫使你从应用层隔离"核心域"。

最新更新