Spring -- setter injection and constructor Injection
First, write a common structure:
Here, UserDao and UserManagerImpl are interfaces between layers.
The following uses these classes to demonstrate the setter injection and constructor injection to solve the Dao injection problem at the Manager layer.
1. setter Injection
First, define the private member variable of Dao in the Manager implementation class, and add the set Method to the variable. During the injection, the set method is automatically called to assign values to the member variable.
Then define the dependency in the configuration file:
Introduce userDao4Mysql into the tag in property, and configure the specific implementation class of the Dao layer in the managerImpl implementation class. If you need to change it, you only need to change it to the bean configured above.
BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml"); UserManager userManager=(UserManager)beanFactory.getBean("UserManagerImpl");userManager.add("dd","d");
The process of calling Manager is as follows:
Injection not used:
@ Overridepublic void add (String username, String password) {// Our application is responsible for service (object) Locating UserDao userDao = new UserDaoForMysqlImpl (); userDao. addUser (username, password );}
After the injection is used, the userDao object has been injected. You do not need to worry about the implementation of the injection:
@Overridepublic void add(String username, String password) {userDao.addUser(username,password);}
Anyway, removes the manual new process and no longer writes the code to death.
2. constructor Injection
In the Manager implementation class:
public UserManagerImpl(UserDao userDao) {this.userDao = userDao;}
The member variables to be injected are put into the constructor and injected when the implementation class is initial.
Configure the injection relationship:
Two injection methods:
When many member variables need to be injected, constructor injection may be troublesome. Therefore, setter injection is recommended.