Spring(二)之构造函数注入

Spring的构造函数注入

在上一篇文章提到Spring可以降低程序之间的依赖,依靠的是将对象的创建交给Spring。
但是当我的类中无默认的构造函数或是构造函数被覆盖重写,那此时即使我的对象创建了,也无法调用类中的方法。

这篇笔记主要是介绍在Spring中进行构造函数的参数注入,首先我们先将原来是UserServiceImpl的类进行改造,给它一个带参的构造函数,从而覆盖掉原来的默认构造函数

public class UserServiceImpl implements IUserService {
    
    
    private String name;
    private Integer age;
    private Date birthday;

 
    public UserServiceImpl(String name, Integer age, Date birthday) {
    
    
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void queryAll() {
    
    
        System.out.println(name+","+age+","+birthday+".");
    }
}

那么在bean.xml中,有一个 constructor-arg 标签,该标签有以下属性

  • type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
  • index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。参数的位置是从0开始
  • name:用于指定给构造函数中指定名称的参数赋值
  • value:用于提供基本数据类型和String类型的数据
  • ref:用于指定其他的bean类型数据。如上面的Date

有了以上的属性,我们可以用常用的name和value进行构造函数的注入

    <bean id="UserService" class="com.imis.service.impl.UserServiceImpl">
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="name" value="mike"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
    <bean id="now" class="java.util.Date"></bean>
public static void main(String[] args) {
    
    
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean
        IUserService is=ac.getBean("UserService",IUserService.class);
        is.queryAll();
    }
mike,18,Sun Jan 17 14:41:03 CST 2021.

猜你喜欢

转载自blog.csdn.net/weixin_45925906/article/details/112743981