Spring framework construction injection type attribute instance explanation

Time:2021-1-2

This article mainly introduces the spring framework construction injection type attribute instance explanation, in this article through the example code introduction is very detailed, has the certain reference learning value to everybody’s study or the work, needs the friend to be possible to refer

Test, verify a problem, no more nonsense, compare the code

package service.impl;

import service.UserService;
import dao.UserDao;
import entity.User;

/**
 *User business class to realize the business management of user function
 */
public class UserServiceImpl implements UserService {

  //Declare the reference of the interface type and decouple the concrete implementation class
  private UserDao dao;
  private String s1;
  private String s2;
  private int i1;
  

  //Generating nonparametric construction method
  public UserServiceImpl() {

  }

  //The construction method with parameters is used to assign values to Dao
  public UserServiceImpl(UserDao dao) {
    this.dao = dao;
  }
  public UserServiceImpl(UserDao dao,String s1) {
    this.dao = dao;
    this.s1=s1;
  }
  public UserServiceImpl(String s2,UserDao dao) {
    this.dao = dao;
    this.s2=s2;
  }
  public UserServiceImpl(int i1,UserDao dao) {
    this.dao = dao;
    this.i1=i1;
  }


  public UserDao getDao() {
    return dao;
  }

  //The setter accessor of Dao property will be called by spring to implement setting value injection
  public void setDao(UserDao dao) {
    this.dao = dao;
  }

  public void addNewUser(User user) {
    //Call the method of user Dao to save user information
    dao.save(user);
    System.out.println("s1="+s1);
    System.out.println("s2="+s2);
    System.out.println("i1="+i1);
  }
}

Core profile:

<bean>
<! -- Construct injection through constructor
<constructor-arg>
  <ref bean="userDao" />
</constructor-arg>
<constructor-arg>
  <value>123</value>
</constructor-arg>
</bean>

Results of operation:

Save user information to database
s1=null
s2=123
i1=0

It can be seen that there is no value attached, which is I1 variable

Solution: modify the core configuration file and use the type attribute to specify the data type

Results of operation:

Save user information to database
s1=null
s2=null
i1=123

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.