[英]Developing A Spring web-app using two different contexts
第2.3节使用场景,有一段像这样
有时情况不允许您完全切换到其他框架。 Spring框架不会强迫您使用其中的所有内容; 这不是一个全有或全无的解决方案。 使用Struts,Tapestry,JSF或其他UI框架构建的现有前端可以与基于Spring的中间层集成在一起,从而可以使用Spring事务功能。 您只需要使用ApplicationContext连接业务逻辑并使用WebApplicationContext集成您的Web层。
现在我无法理解最后一句话。 我们如何使用ApplicationContext连接业务逻辑并使用WebApplicationContext与Web层集成。 我们怎样才能做到这一点? 他们谈论的网络层是否包含控制器和jsps?
据我所记得,如果我们需要一个类中的任何对象,我们只需将它们自动接线即可,其余的工作将由spring进行。
有人可以提供示例解释。 当我刚开始学习春天时,请原谅我的无知。
如果有人问类似的问题,可以请我指出正确的方向
您可以设置两个甚至三个不同的项目或模块,每个项目或模块都有各自的上下文。 例如,一个带有WebApplicationContext的Web项目正在呈现视图并调用业务方法,即从业务层使用平稳的Web服务。 并设置一个单独的项目或模块来处理具有自己的上下文文件和Bean的业务。 甚至一个Commons项目都包括Web和业务层之间的共享bean。
即使您可以分层创建多个不同的上下文,也是有可能的。
我将同时给出分层和非分层的两个答案。 我将同时使用基于Java的配置。 我将针对两个上下文给出答案,但是您可以针对许多上下文来实现。
1)非等级制
创建两个不同的context.xml
,假设context1.xml
和context2.xml
。 context1.xml应该是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=..... some imports >
<context:annotation-config />
<context:component-scan base-package="desiredPackage1" />
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>db.properties</value>
</list>
</property>
</bean>
<context:property-placeholder properties-ref="properties"/>
仅用于context2.xml更改
<context:component-scan base-package="desiredPackage2" />
然后创建一个Configuration.java
类,如下所示:
public class Config {
public static void main(String[] args) throws Exception {
ApplicationContext desiredContext1 = new ClassPathXmlApplicationContext("file:////...path.../context1.xml");
ApplicationContext desiredContext2 = new ClassPathXmlApplicationContext("file:////...path.../context2.xml");
}
}
现在您有两个不同的上下文,如果要按层次进行操作,请像下面这样更改main方法: 2)层次结构
public class Config {
public static void main(String[] args) throws Exception {
ApplicationContext desiredContext1 = new ClassPathXmlApplicationContext("file:////...path.../context1.xml");
String[] congigPath = new String[1];
congigPath[0] = "file:////...path.../context2.xml";
ApplicationContext desiredContext2 = new ClassPathXmlApplicationContext(congigPath,desiredContext1);
}
}
在这种情况下,desiredContext2对象可以看到desiredContext1对象,但desiredContext1对象不能看到desiredContext2对象。
如果您要在构建网络应用时使用它,请在配置类中使用此注释,
@Configuration
@ImportResource("context1.xml", "context2.xml")
public class Config { ....
希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.