现在有 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" );