一个spring例子


package eg;

public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;


public AnotherBean getBeanOne() {
return beanOne;
}

public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}

public YetAnotherBean getBeanTwo() {
return beanTwo;
}

public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
}

package eg;

import java.awt.Color;
import java.util.Locale;

public class AnotherBean {
private Color color;
private Locale locale;


public Color getColor() {
return color;
}

public void setColor(Color color) {
this.color = color;
}


public Locale getLocale() {
return locale;
}

public void setLocale(Locale locale) {
this.locale = locale;
}
}

package eg;

import java.util.Properties;

public class YetAnotherBean {
private Properties properties;


public Properties getProperties() {
return properties;
}

public void setProperties(Properties properties) {
this.properties = properties;
}
}


上面的代码中,我们看出ExampleBean引用了AnotherBean和YetAnotherBean, 这里就牵扯到什么时候将AnotherBean和YetAnotherBean和ExampleBean的关系建立起来,在spring中通过配置文件, 由spring的容器自己注入关系,如下:
配置文件kissesmlBeanFactory.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="eg.ExampleBean">
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<property name="beanTwo">
<ref bean="yetAnotherBean"/>
</property>
</bean>
<beans>


那么我们如何得到ExampleBean或者其他的Bean实例呢?


public class XmlBeanFactoryEx {

public static void main(String[] args) {
try{


InputStream is = new FileInputStream(new File("XmlBeanFactory.xml"));

BeanFactory beanFactory = new XmlBeanFactory(is);
ExampleBean ebOne = (ExampleBean)beanFactory.getBean("exampleBean");
ExampleBean ebTwo = (ExampleBean)
System.out.println(ebOne);


}catch(Exception e){
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值