1. Manual Injection
(1) Set injection
Public class userservice { private Userdao Userdao; Public void Setuserdao (Userdao dao) { this. userdao = dao; }}
class= "Com.spring1.dao.UserDao" ></bean> class= " Com.spring1.service.UserService "> <property name=" Userdao "ref=" UserDao1 "></property> </bean>
The USERDAO1 is injected through the Setuserdao method of the UserService object.
Public classUser {intID; String name; String password; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; }}
Public class Userdao { publicvoid setshowuser (user user) { System.out.println ( User.getid ()+ ":" +user.getname () + ":" +User.getpassword ());} }
class= "Com.spring1.entity.User" > <property name= "id" value= "1" ></property> < Property name= "Name" value= "Zhangsan" ></property> <property name= "password" value= "123456" >< /property> </bean> class= "Com.spring1.dao.UserDao" > <property name= " Showuser "ref=" user "></property> </bean>
Initializes the user in the bean configuration, userDao1 the user by its own Setshowuser method
(2) Construction method injection
class= "Com.spring1.dao.UserDao" > </bean> class= " Com.spring1.service.UserService "> <constructor-arg name=" UserDao1 "ref=" UserDao1 "></ Constructor-arg> </bean>
@Test publicvoid Test () { new Classpathxmlapplicationcontext ("Applicationcontext.xml"); = (UserService) ac.getbean ("Testservice"); Service.showuser (); }
Public class userservice { private Userdao Userdao; Public UserService (Userdao userDao1) { this. Userdao = Userdao; } Public void Showuser () { System.out.print ("OK-------------"); } }
The name of the constructor parameter, corresponding to the name of the constructor parameter of the class.
2. Automatic injection
class= "Com.spring1.dao.UserDao" ></bean> class= "Com.spring1.service.UserService" Autowire= "ByName" > </bean>
Id=userdao2, the Setuserdao2==userdao2 below is the same.
Public class userservice { private Userdao Userdao; Public void SetUserDao2 (Userdao userDao1) { this. Userdao = userDao1; } Public void Showuser () { userdao.showuser (); } }
When ByName is automatically injected, it is necessary to top a bean with a parameter name in the Name= class
Spring's Dependency Injection di (IOC)