how to reference a bean of another xml file in spring

前端 未结 6 1357
花落未央
花落未央 2020-12-07 17:30

I have a Spring bean defined in an xml file. I want to reference it from another xml file. How can I go about it?

6条回答
  •  星月不相逢
    2020-12-07 18:30

    You may also go about this by loading multiple Spring bean configuration files in the code :

    ApplicationContext context = new ClassPathXmlApplicationContext(
        new String[] {"Spring-Common.xml", "Spring-Connection.xml","Spring-ModuleA.xml"});
    

    Put all spring xml files under project classpath:

    project-classpath/Spring-Common.xml
    project-classpath/Spring-Connection.xml
    project-classpath/Spring-ModuleA.xml
    

    However, the above implementation is a lack of organizing and error prone, the better way should be organized all your Spring bean configuration files into a single XML file. For example, create a Spring-All-Module.xml file, and import the entire Spring bean files like this :

    
    
        
        
        
    
    
    

    Now you can load a single xml file like this :

    ApplicationContext context = 
        new ClassPathXmlApplicationContext(Spring-All-Module.xml);
    

    Note In Spring3, the alternative solution is using JavaConfig @Import.

提交回复
热议问题