SpringDI Setter injection and springdisetter Injection
Dependency injection (DI) is a process through which objects can be passed through the constructor parameters, factory method parameters or properties set after the object instance is constructed or returned to define their Dependencies from the factory method. Then, the container injects These dependencies when creating the bean. This process is basically the opposite, so it is called control inversion (IoC ), it uses the direct construction of classes or the service locator mode to control the instantiation or location of its own dependencies.
In DI implementation, the most common method is to use the settern method to implement our property injection,
For more information about dependency injection (DI), see Spring dependency injection (DI).
1. Prepare the property data UserDao and UserService
/*** @ Author Shanghai shangxue * learn more + V: java8733 ***/public class UserDao {public String userLogin () {return "I am UserDao -----> userLogin ();}}
We need to inject UserDao into UserService.
/*** @ Author Shanghai shangxue * learn more V: java8733 */public class UserService {private UserDao userDao; public void userLogin () {String res = userDao. userLogin (); System. out. println (res);} public void setUserDao (UserDao userDao) {this. userDao = userDao ;}}
2. Spring config file spring-config.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id = "userDao" class = "com. shsxt. demo. userDao "> </bean> <! -- The First setter injection --> <bean id = "userService" class = "com. shsxt. demo. userService "> <property name =" userDao "ref =" userDao "> </property> </bean> </beans>
In bean labels, property attributes are used to inject attributes.
3. Notes
Through the above configuration, we will complete the setter injection method. Note that we need to provide the setter Method for attributes.
Shanghai shangxuexiang's original java training. For more information or technical support, click here.