Two ways of dependency injection of Bean

Bean dependency injection has two ways

note! What I'm talking about here are the dependency injection methods of common data types.
1. Set method
This method is the most commonly used bean dependency injection method. First, the attributes in the class that need to be injected must contain the set method! Here I give an example, I have a User class, I need to perform dependency injection on the uid attribute

public class User{
    
    
	private String uid;
	public void setUid(String uid){
    
    
		this.uid = uid;
	}
}

As can be seen from the above code, my uid attribute in the User class contains a set method, and then I need to configure the corresponding dependency injection in the configuration file

<bean id="uid" class="User" >
	<property name="uid" value="1234">
</bean>

At this time, when testing, the output uid will be 1234.

2. Parameter construction method injection
First of all, a parameter construction method is needed, or use the User example just now

public class User{
    
    
	private String uid;
	public User(String uid){
    
    
		this.uid = uid;
	}

	// 为了不影响其他的框架使用,推荐无论什么时候都多写一个有参构造方法
	public User(){
    
    
	}
}

Only the inner label is different in the configuration file, not the property label, but the constructor-arg label

我需要在配置文件中配置对应的依赖注入

<bean id="uid" class="User" >
	<constructor-arg name="uid" value="1234"></constructor-arg>
</bean>

The operation result is the same as the set method

The above is my own learning experience, if there is any inappropriateness, please correct me.

Guess you like

Origin blog.csdn.net/interestANd/article/details/112554965