Spring 加载原模块和其他模块里的多个applicationContext.xml

现在有 A B C 三个模块,都是spring项目,

A项目

-------AService.java

-------spring-a.xml


B项目

-------BService.java

-------spring-b.xml



C项目

------Cservice.java

------------------AService属性(get和set方法)

------------------BService属性(get和set方法)

-----spring-c.xml



在模块C中通过dependency依赖 A B两个模块,实现注入AService BService的步骤如下:

spring-c.xml 配置:

<bean id="cservice" class="com.test.acount.acount_service.Cservice">
<property name="aService" ref="aService"></property>

<property name="bService" ref="bService"></property>
</bean>

其中ref要和相应模块的bean id 相同;



代码创建ClassPathXmlApplicationContext,需要使用全部的applicationContext.xml,格式为String[]

String[] paths = { "spring-a.xml", "spring-b.xml","spring-c.xml" };
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext(paths);
Cservicebean = (Cservice) app.getBean("cservice");

这样就可以注入其他模块spring配置的bean了。


------------------------------------------------------------------------------------

如果C项目是web项目,使用A B里的服务,可以做如下配置:

web.xml 加载全部模块的spring配置

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
  classpath:/spring-a.xml

classpath:/spring-b.xml

  </param-value>
  </context-param>
  <listener>
  <listener-class>
  org.springframework.web.context.ContextLoaderListener
  </listener-class>
  </listener>


在servlet里可以这样获取 ApplicationContext ,需要重写init方法

 private ApplicationContext context;


    @Override
    public void init()
        throws ServletException
    {
        super.init();
        context = WebApplicationContextUtils.getWebApplicationContext( getServletContext() );
    }


有了context,可以获取Service

AServiceservice = (AService) context.getBean( "aService" );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值