IOC中创建对象的方式

IOC创建对象的方式
xml文件中的:constructor-arg与property都是依赖注入的方式

constructor-arg:通过构造函数注入。 则property:通过setxx方法注入。

1.使用无参构造函数

package com.liang.pojo;

public class User {
    private String name;
    public User(){
        System.out.println("User的无参构造");
    }

    public String getName() {
        return name;
    }

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

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="user" class="com.liang.pojo.User">
        <property name="name" value=""/>
    </bean>
</beans>
import com.liang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       User user=(User) context.getBean("user");
       user.show();
    }
}

结果为:

User的无参构造
name=为

2.使用有参构造函数

package com.liang.pojo;

public class User {
    private String name;
//    public User(){
//        System.out.println("User的无参构造");
//    }
 public User(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="user" class="com.liang.pojo.User">
        <constructor-arg name="name" value="直接通过参数名赋值"></constructor-arg>
    </bean>

第二种xml:通过下标赋值

<bean id="user" class="com.liang.pojo.User">
    <constructor-arg index="0" value="下标赋值"></constructor-arg>
    </bean>

第三种xml:通过类型赋值,当有多个变量的时候不合适

<bean id="user" class="com.liang.pojo.User">
       <constructor-arg type="java.lang.String" value="通过类型创建,当有多个变量时不适合"/>
<bean id="user" class="com.liang.pojo.User">

注:在配置文件加载的过程中容器中管理的对象就已经初始化了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值