The previous article mentioned the constructor injection, but sometimes the constructor injection is not very useful, now look at the set injection.
Constructor Injection Blog Address: http://blog.csdn.net/luckey_zh/article/details/46671307
Take a look at the following example:
public class Roles {private int id;private String rolename;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getrolename () {return roleName;} public void Setrolename (String roleName) {this.rolename = RoleName;} Override the ToString method to facilitate testing of @overridepublic String toString () {return "Roles [id=" + ID + ", rolename=" + RoleName + "]";}}
Spring Configuration:
<bean id= "Roles" class= "Cn.com.ztz.spring.model.Roles" ><property name= "id" value= "2"/><property name = "RoleName" value= "Administrator"/></bean>
Test the Main method:
public static void Main (string[] args) {ApplicationContext context = new Classpathxmlapplicationcontext ("Classpath: Applicationcontext.xml "); Roles r= (Roles) Context.getbean ("Roles"); System.out.println (R.tostring ());}
Output Result:
Roles [id=2, rolename= Administrator]
looking at the spring configuration, we can see that constructors <constructor-arg/> Set injection are <property/>
A bean that references other beans is similar, see the example below
public class Roles {private int id;private String rolename;private Users users;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getrolename () {return roleName;} public void Setrolename (String roleName) {this.rolename = RoleName;} public void Setusers (users users) {this.users = users;} Public Users Getusers () {return users;} Rewrite the tostring method to facilitate testing @overridepublic String ToString () {return "Roles [id=" + ID + ", rolename=" + RoleName + ", users=" + US ERs + "]";}}
public class Users {private int id;private String name;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic String toString () {return "Users [id=" + ID + ", name=" + name + "]";}}
Spring Configuration:
<bean id= "Roles" class= "Cn.com.ztz.spring.model.Roles" ><property name= "id" value= "2"/><property name = "RoleName" value= "Administrator"/><property name= "users" ref= "users"/></bean><bean id= "users" class= " Cn.com.ztz.spring.model.Users "><property name=" id "value=" 2 "/><property name=" name "value=" Zhang San "/> </bean>
Run the test method above to output the result:
Roles [id=2, rolename= Administrator, Users=users [id=2, Name= Zhang San]]
Spring Set Injection