java什么时候创建对象_Java Spring框架在何时创建对象的实验

结论:Spring在创建spring容器的时候就创建的类的对象(调用了类的无参构造方法)

1. 下面我们创建一个Person类用于测试

packagecom.mars.learnspring;importcom.sun.xml.internal.ws.addressing.WsaActionUtil;public classPerson {privateString name;privateString gender;privateInteger age;privateString email;publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicString getGender() {returngender;

}public voidsetGender(String gender) {this.gender =gender;

}publicInteger getAge() {returnage;

}public voidsetAge(Integer age) {this.age =age;

}publicString getEmail() {returnemail;

}public voidsetEmail(String email) {this.email =email;

}

@OverridepublicString toString() {return "Person{" +

"name='" + name + '\'' +

", gender='" + gender + '\'' +

", age=" + age +

", email='" + email + '\'' +

'}';

}

//注意:下面的无参构造方法用于测试publicPerson() {

System.out.println("Person类的无参构造方法...");

}

}

2.下面是ioc反转控制的xml文件

3. 下面是maven里面创建的测试类

packagecom.mars.springtest;import static org.junit.Assert.*;importcom.mars.learnspring.Person;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;public classPersonTest {

@Testpublic voidtest() {

ApplicationContext ioc=new ClassPathXmlApplicationContext("conf/ioc.xml");

//注意,下面两句被注释掉了,目的就是用来看看无参构造方法何时被调用//Person bean=(Person) ioc.getBean("person01");//System.out.println(bean);

}

}

4.执行上面第3部的测试类。其结果如下

"C:\Program Files\Java\jdk1.8.0_221\bin\java.exe"...

Person类的无参构造方法...

Process finished with exit code0

5.由此可见类的构造方法是子spring容器启动就被调用了。

6.01ioc反转控制里面配置多少个bean就会创建多少个相应的对象

6.02 同一个bean被调用两次,但这个bean对于的对象只会创建一个。

如下代码,我们调用了两次person01这个bean,但是它创建的对象却还是一个而不是两个,所以system.out里面输出结果为true。

@Testpublic voidtest() {

ApplicationContext ioc=new ClassPathXmlApplicationContext("conf/ioc.xml");

Person bean1=(Person) ioc.getBean("person01");

Person bean2=(Person) ioc.getBean("person01");

System.out.println(bean1==bean2);

}

输出结果

Person类的无参构造方法...

Person类的无参构造方法...trueProcess finished with exit code0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值