Spring (2) constructor injection

Spring's constructor injection

In the previous article, it was mentioned that Spring can reduce the dependence between programs, relying on the creation of objects to Spring.
But when there is no default constructor in my class or the constructor is overwritten, then even if my object is created, the methods in the class cannot be called.

This note mainly introduces the parameter injection of the constructor in Spring. First, we first transform the class that was originally UserServiceImpl and give it a constructor with parameters, thereby overwriting the original default constructor.

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+".");
    }
}

Then in bean.xml, there is a constructor-arg tag with the following attributes

  • type: used to specify the data type of the data to be injected, the data type is also the type of one or some parameters in the constructor
  • index: Used to assign the data to be injected to the parameter at the specified index position in the constructor. The position of the parameter starts from 0
  • name: Used to assign a parameter to the specified name in the constructor
  • value: used to provide basic data types and String type data
  • ref: used to specify other bean type data. As the Date above

With the above attributes, we can use commonly used name and value for constructor injection

    <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.

Guess you like

Origin blog.csdn.net/weixin_45925906/article/details/112743981