5_515自己的收获关于IOC+DI注入+三种实例化Bean+Spring的生命周期

这一段代码:application.xml中的一个bean 是IOC的简单应用
其中可以在一个类中通过
@Test
public void show001() {
/将对象放到容器中(控制),再从容器中取对象(反转)/
ApplicationContext app = new ClassPathXmlApplicationContext(“classpath:application.xml”);**
//加载:application.xml**
Boy boy2 = (Boy)app.getBean(“boy”);//获取对象返回的类型是Object类型
boy2.say();
}
第二步:从容器中取对象(反转);
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
DI依赖注入:


//我的理解就是boy给Girl的属性 private Boy b;其实目的:b = new Boy();
不加属性 ;其实就是 private Boy b=null;


//在一个类中测试 @Test//需要导包 public void show002() { /*将对象放到容器中(控制),再从容器中取对象(反转)*/ ApplicationContext app = new ClassPathXmlApplicationContext("classpath:application.xml");
Girl g =   (Girl)app.getBean("girl");
g.say_Girl();//say_Girl中有方法 b.say();

第一种实例化bean:直接返回对象

一个类中测试

@Test
public void show03(){
//加载application.xml

    ApplicationContext app = new ClassPathXmlApplicationContext("classpath:application.xml");
    //获取一个对象   , 返回值类型Object;
    PersonService ps3  = (PersonService)app.getBean("personservice");
    ps3.show();
}

第二种实例化bean:在bean中可以调用静态getCreateObject();
//其中的getCreateObject是静态方法;返回是PersonService(接口)类型《父类》

@Test
public void show04(){
//加载application.xml
ApplicationContext ap = new ClassPathXmlApplicationContext(“classpath:application.xml”);
//其中调用getCreateObject()返回PersonService对象;
PersonService pss = (PersonService) ap.getBean(“createObjectPersonService”);
pss.show();

}
第三种方法://其中的getCreateObjectPersonService2不是静态方法

<bean id ="createObject2" factory-bean="createObjectPersonService2" 
factory-method="getCreateObjectPersonService2"></bean>
通过对象createObjectPersonService2调用非静态方法getCreateObjectPersonService2
返回值是PersonService类型的


@Test
public  void show05(){
//加载application.xml
    ApplicationContext aps= new ClassPathXmlApplicationContext("classpath:application.xml");
           aps其实是通过createObjectw对象调用 getCreateObjectPersonService2返回Object类型;
              PersonService pss = (PersonService)aps.getBean("createObject2");
              pss.show();

}

//开启懒加载的好处是当bean中有多个对象时,当调用对象时才new对象给服务器减压

<!--多例模式-->
<bean id="person2" class="com.offcn.pojo.Person" scope="prototype"></bean>

//

类ObjectBean
public ObjectBean(){
System.out.println(“this ObjectBean构造器”);

}
public void show(){
    System.out.println("show==");
}
public void init(){
    System.out.println("init===");
}
public void dest(){
    System.out.println("destory===");
}

}

测试:
@Test
public void show001(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(“classpath:application.xml”);
ObjectBean bean1 = (ObjectBean) app.getBean(“objectBean”);
bean1.show();
app.close();
}
先执行: 构造器:执行流程

《1》“this ObjectBean构造器”
《2》“init===”
《3》“show==”
《4》"destory==="

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值