第一步:新建工程 SecondSpring
工程目录结构如下:
第二步:导入相应的jar包
略...
第三步:新建类
InnerBean.java
package com.xuzhiwen.spring2; public class InnerBean { private int id; private String name; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } @Override public String toString() { return "InnerBean [id=" + id + ", name=" + name + "]"; } public void inner(){ System.out.println(this); System.out.println("InnerBean.inner()..."); } }
第四步: 新建类
OutterBean.java
package com.xuzhiwen.spring2; public class OutterBean { private InnerBean innerBean; public void setInnerBean(InnerBean innerBean) { this.innerBean = innerBean; } public OutterBean(InnerBean innerBean) { this.innerBean = innerBean; } public void outter(){ System.out.println("OutterBean.outter()..."); innerBean.inner(); } }
第五步:新建配置文件
innerbean.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="outter" class="com.xuzhiwen.spring2.OutterBean">
<!--setter 方式注入--> <property name="innerBean"> <bean class="com.xuzhiwen.spring2.InnerBean"> <property name="id" value="2" /> <property name="name" value="test1" /> </bean> </property>
<!--构造器 方式注入--> <!-- <constructor-arg> <bean class="com.xuzhiwen.spring2.InnerBean"> <property name="id" value="2" /> <property name="name" value="test1" /> </bean> </constructor-arg> --> </bean> </beans>
第六步:新建配置文件
common.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource="xmlfolder/app1.xml" /> <import resource="xmlfolder/innerbean.xml" /> </beans>
第七步:新建测试类
Test.java
package com.xuzhiwen.spring2; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("common.xml"); OutterBean out = (OutterBean) app.getBean("outter"); out.outter(); } }
第八步: 运行结果如下