使用构造器实例化bean:
springday02:(同样导入5个基本jar包)
1.复制xml文件到ioc包下2.B类,实现无参构造器3.A类,B是它的成员变量,实现无参和set/get方法4.修改xml中,实现构造器实例化bean,注意,因为A类中使用到了B对象,所以需要ref属性5.测试A.java:
package container.ioc;
public class A {
private B b;
public B getB() { return b; } public void setB(B b) { this.b = b; } public A(){ System.out.println("A的无参构造器"); } public A(B b){ this.b = b; }}B.java:
package container.ioc;
public class B {
public B(){
System.out.println("B的无参构造器"); }}xml:
<bean id="b1" class="container.ioc.B" />
<bean id="a1" class="container.ioc.A"> <constructor-arg index="0" ref="b1"></constructor-arg> </bean>TestCase:
package container.ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestCase {
@Test
public void test1(){ String cfg = "container/ioc/applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(cfg); A a = ac.getBean("a1",A.class); System.out.println(a); }}测试结果: