Spring-第六章:构造注入

	注⼊:通过Spring的配置⽂件,为成员变量赋值
	Set注⼊:Spring调⽤Set⽅法 通过配置⽂件 为成员变量赋值
	构造注⼊:Spring调⽤构造⽅法 通过配置⽂件 为成员变量赋值

开发步骤

  • 提供有参构造方法
public class customer implements Serializable {
    private String name;
    private int age;

    public customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "customer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • Spring的配置文件
<!--参数注入的方法-->
    <bean id="Customer" class="Dao.constracter.customer">
        <constructor-arg>
            <value>lty</value>
        </constructor-arg>
        <constructor-arg>
            <value>150</value>
        </constructor-arg>
    </bean>
  • 测试的方法
 @Test
   public void test02(){
       ApplicationContext cxc = new ClassPathXmlApplicationContext("applicationContext.xml");
       customer customer = cxc.getBean("Customer", customer.class);
       System.out.println("customer = " + customer);
   }
  • 运行结果
    在这里插入图片描述

2构造方法重载

2.1参数个数不同时

通过控制<constructor-arg>标签的数量进⾏区分

2.2构造参数个数相同时

通过在标签引⼊ type属性 进⾏类型的区分 <constructor-arg type="">

3.注入的总结

未来的实战中,应用set注入还是构造注入呢?
答案:set注入会更多
	1.构造注入麻烦(重载)
	2.Spring框架底层 大量应用了set注入

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_47298981/article/details/107576606