public class ExampleBean {
private String psnName=null;
private RefBean refbean=null;
private String addinfo=null;
public String getAddinfo() {
return getRefbean().getAddress()+getRefbean().getZipcode();
}
public String getPsnName() {
return psnName;
}
public void setPsnName(String psnName) {
this.psnName = psnName;
}
public void setRefbean(RefBean refbean) {
this.refbean = refbean;
}
public RefBean getRefbean() {
return refbean;
}
public void setAddinfo(String addinfo) {
this.addinfo = addinfo;
}
}
RefBean类:
public class RefBean {
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
private String zipcode=null;
private String address=null;
}
其xml配置文件 Bean.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="exampleBean" class="test.ExampleBean">
<property name="psnName"><value>xkf</value></property>
<property name="refbean">
<ref bean="refBean"/>
</property>
</bean>
<bean id="refBean" class="test.RefBean">
<property name="address"><value>BeiJing</value></property>
<property name="zipcode"><value>100085</value></property>
</bean>
</beans>
然后可以写个测试类来测试,当然,需要Spring中的Spring-core.jar以及commons-logging.jar,当然在elipse中可以通过安装spring-ide插件来轻松实现。
public class Test {
public static void main(String[] args){
try{
Resource input = new ClassPathResource("test/Bean.xml");
System.out.println("resource is:"+input);
BeanFactory factory = new XmlBeanFactory(input);
ExampleBean eb =
(ExampleBean)factory.getBean("exampleBean");
System.out.println(eb.getPsnName());
System.out.println(eb.getAddinfo());
}
catch(Exception e){
e.printStackTrace();
}
}
这样,通过BeanFactory的getBean方法,以及xml配置文件,避免了在test类中直接实例化ExampleBean,消除了应用程序(Test)与服务(ExampleBean)之间的耦合,实现了IOC(控制反转)或者说实现了依赖的注射(Dependency Injection)。
本文地址:http://com.8s8s.com/it/it13215.htm