Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we declare </context:component-scan>separately in applicationContext.xml and dispatcher-servlet.xml

Why sometimes we separately declare context:component-scan

in applicationContext.xml we declare like below:

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

in dispatcher-servlet.xml we declare like below:

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

Why don't we just declare in applicationContext.xml as below :

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

Then all component annotated @Controller,@Service,@Repository will be detected

like image 629
Enosh Avatar asked Jun 18 '26 05:06

Enosh


1 Answers

This separation is meant to allow multiple dispatcher servlets to be defined and the core business components to be reused.

Usually, you'll have stuff like repositories and services defined in the application-context.xml and bound to the entire servlet-context (by using a ContextLoaderListener) and have one or more dispatcher servlets defined, each with their own (child) context (consisting of controllers and mvc utility components) which will reuse the same beans from the parent context.

I would say this separation makes sense even if you have a single dispatcher, as it forces you to isolate the "core domain" from the application layer.

like image 123
Costi Ciudatu Avatar answered Jun 20 '26 14:06

Costi Ciudatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!