Spring: Okay to have two contexts - web & backend?
I have a spring-base web app with a spring-based backend. Currently, the integration is done in a stupid way of manual copying the backend .xml's to the web app resources and merging.
I was wondering whether Spring is ready to have a bean which would be another ApplicationContext
, and whether it can get beans from it; als开发者_Go百科o if it handles bean name collisions - e.g. if I can assign a namespace to the "imported" beans.
Or - what is the best practice for this case?
Thanks, Ondra.
I always split my Spring XML by layer: web, service, persistence. It's never just in one file. I'd say it's beyond okay to do that; it's a best practice.
By default, you should already have two contexts. The context named after your servlet ( [servlet-name]-context.xml )is a WebApplicationContext and is a child context of the main ApplicationContext, which is created from the files listed in the contextConfigLocation and loaded by the ContextLoaderListener. The child can access any beans defined in the parent, but the parent has no access to beans defined in the child, so keep that in mind before you start moving beans around.
I keep only web-specific configuration in the WebApplicationContext - my controllers and views and such. Anything that isn't specific to the web goes into the main ApplicationContext, which is itself always a single file which just imports a number of other application context xml files, broken down by layer, as suggested by others.
<import resource="classpath:dao-context.xml" />
<import resource="classpath:service-context.xml" />
<import resource="security-context.xml" />
Note, spring only allows a single property-placeholder element in each application context, but you can have one in each child app context as well, so my [servlet-name]-context.xml file always has a property-placeholder with web-specific config properties and the main application context has a different one, which I usually define right in the top level file, before all of the imports.
If I've understood you correctly, this is definitely OK. Some people split their database contexts with their web contexts. Example below in your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:someApplicationContext.xml
classpath:someOtherApplicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
As for the collision of beans - you should be giving beans a unique ID.
精彩评论