会计考友 发表于 2012-8-4 12:44:44

Java认证辅导之关于Spring使用入门示例3

Java认证辅导之关于Spring使用入门示例3
3.5.添加引用
org.springframework.core-3.0.2.RELEASE.jar
org.springframework.beans-3.0.2.RELEASE.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
3.6.hellospringworld.xml
代码
《?xml version=“1.0” encoding=“UTF-8”?》
《!DOCTYPE beans PUBLIC “-//SPRING/DTD BEAN/EN” “http://www.springframework.org/dtd/spring-beans.dtd”》
《beans》
《bean id=“LanguageBean” class=“example.PerlLanguage”》
《/bean》
《bean id=“DeveloperBean” class=“example.Developer”》
《property name=“language” ref=“LanguageBean”/》
《/bean》
《/beans》
3.7.Main.java
代码
package example;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r = new FileSystemResource(“hellospringworld.xml”);
BeanFactory f = new XmlBeanFactory(r);
Developer d = (Developer) f.getBean(“DeveloperBean”);
String s = d.getCurrentUsingLanguage();
System.out.println(“The developer is currently using: ”+s);
}
}
运行此程序可以看到输出是:
The developer is currently using: Perl
现在,假设有一天这个Developer不使用Perl而改用Java了,我们需要做什么?我们并不需要改程序,只需要修改xml文件就行了。
《bean id=“LanguageBean” class=“example.PerlLanguage”》《/bean》
改成
《bean id=“LanguageBean” class=“example.JavaLanguage”》《/bean》
这就是我目前所理解的使用Spring的好处,即解耦,减少不同的类之间的耦合性。
当然,现在的Spring已经日渐复杂跟强大,其中很多特性我并没有使用过,上面所说都是些粗浅的理解,等待以后使用的过程中有更加深入的认识。
页: [1]
查看完整版本: Java认证辅导之关于Spring使用入门示例3