首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring对象属性的流入

2012-10-06 
spring对象属性的注入注入:为对象的属性赋值1.基本数据类型的set注入public class User { private int use

spring对象属性的注入

注入:为对象的属性赋值

1.基本数据类型的set注入

public class User { private int userid; private String username; private String password;}

?
为此类添加getter和setter
配置文件:

<bean id="user" value="1"></property> <property name="password" value="pass_word"></property> <property name="username" value="tom"></property></bean>

?
测试类:

User user = (User)context.getBean("user");

?2.基本数据类型的构造器注入(构造方法)
为User添加构造方法
?

public User(String username, String password) {  super();  this.username = username;  this.password = password; }  public User(int userid, String username, String password) {  super();  this.userid = userid;  this.username = username;  this.password = password; }

?配置文件

<bean id="user" name="code"><constructor-arg value="1" type="int" index="0"></constructor-arg><constructor-arg value="tom" type="String" index="1"></constructor-arg>

?特殊类型数据的注入

public class Student { private int id; private String name; private String [] favor; private Set set; private List list; private Map map; private User user;}

?添加setter 和getter

<!--数组的注入--> <property name="favor">  <list>   <value>上网</value>   <value>足球</value>  </list> </property><!--Set的注入--><property name="set">  <set>   <value>setvalue1</value>   <value>setvalue2</value>  </set></property><!--List的注入--> <property name="list">  <list>   <value>listvalue1</value>   <value>listvalue2</value>  </list> </property><!--Map的注入--> <property name="map">  <map>   <entry key="key1" value="value1"></entry>   <entry key="key2" value="value2"></entry>  </map> </property>

?
自定义类型对象的注入

<bean id="user" type="int" index="0"></constructor-arg> <constructor-arg value="tom" type="String" index="1"></constructor-arg> <constructor-arg value="pass_word"></constructor-arg></bean> <property name="user" >  <ref bean="user"/><!-- 也可以使用local="user" 不过这样的话,只能引用本配置文件中的Bean --> </property>

?

测试代码:

 public static void main(String[] args) {  ApplicationContext context = new ClassPathXmlApplicationContext("com/dowebber/inject/spring.xml");    Student std = (Student) context.getBean("student");    System.out.println(std.getId());  System.out.println(std.getName());  System.out.println(std.getFavor().toString());  System.out.println(std.getList());  System.out.println(std.getSet());  System.out.println(std.getMap());  System.out.println(std.getUser()); }

?

热点排行