Splitting applicationContext to multiple files

前端 未结 5 1799
心在旅途
心在旅途 2020-11-27 11:10

What is the correct way to split Spring\'s configuration to multiple xml files?

At the moment I have

  • /WEB-INF/foo-servlet.xml
5条回答
  •  一整个雨季
    2020-11-27 11:27

    Mike Nereson has this to say on his blog at:

    http://blog.codehangover.com/load-multiple-contexts-into-spring/

    There are a couple of ways to do this.

    1. web.xml contextConfigLocation

    Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

      
           contextConfigLocation 
          
              applicationContext1.xml
              applicationContext2.xml
          
      
    
      
          
              org.springframework.web.context.ContextLoaderListener
          
      
    

    The above uses carriage returns. Alternatively, yo could just put in a space.

      
           contextConfigLocation 
           applicationContext1.xml applicationContext2.xml 
      
    
      
           org.springframework.web.context.ContextLoaderListener 
      
    

    2. applicationContext.xml import resource

    Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.

    In applicationContext.xml you might have…

      
      
    
      
      
    
      
      
    

    Which strategy should you use?

    1. I always prefer to load up via web.xml.

    Because , this allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.

    2. If you are loading contexts into a non-web application, I would use the import resource.

提交回复
热议问题