Spring中IOC创建对象的方式

Spring中IOC创建对象的方式

  1. 通过无参构造器创建对象

实体类:

package com.wbx.test;/*
 *@author 王炳祥
 *@createTime
 */

public class UserTest2 {
    private String name;
    //无参构造器
    public UserTest2(){

        System.out.println("利用无参构造器创建对象");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+name);
    }
}

xml配置代码:

   <bean id="uname2" class="com.wbx.test.UserTest2">

    </bean>

测试代码:

import com.wbx.test.UserTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class mytest {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("userTest.xml");
        //spring一下会getbean全部(此时输出的是UserTest2中的无参构造器中的输出内容)
        UserTest uname = (UserTest) context.getBean("uname");
//        uname.show();
    }
}

在这里插入图片描述

  1. 通过有参构造器创建
    实体类:
package com.wbx.test;/*
 *@author 王炳祥
 *@createTime
 */

public class UserTest {
    private String name;
    public UserTest(String name){

        this.name=name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
     public void show(){
        System.out.println("name="+name);
     }
}

xml文件的配置:

    <bean id="uname" class="com.wbx.test.UserTest">
        <!--第一种,下标赋值-->
        <!--<constructor-arg index="0" value="ai小余"/>-->
        <!--第二种,通过类型创建(如果有参数类型相同,则会出现问题),不推荐使用-->
        <!--<constructor-arg type="java.lang.String" value="1314"/>-->
        <!--第三种,直接通过参数名来设置-->
        <constructor-arg name="name" value="长安"/>
    </bean>

测试代码:

import com.wbx.test.UserTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class mytest {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("userTest.xml");
        //spring一下会getbean全部(此时输出的是UserTest2中的无参构造器中的输出内容)
        UserTest uname = (UserTest) context.getBean("uname");
        uname.show();
    }
}

在这里插入图片描述

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值