1。在配置文件中,用属性赋值
<bean id="user" class="bean.User" >
<!--
用property 给bean赋值
<property name="id" value="10010"/>
<property name="name" value="zwc"/>
<property name="sex" value="1"/>
-->
</bean>
2。在配置文件中,用构造函数赋值【前提条件,必须有构造函数】
<bean id="user" class="bean.User">
<!--
用property 给bean赋值
<property name="id" value="10010"/>
<property name="name" value="zwc"/>
<property name="sex" value="1"/>
-->
</bean>
3。在配置文件中,用初始化方法赋值,
<bean id="user" class="bean.User" init-method="init">
</bean>
init方法,必须在bean.User中定义
4。实现InitializingBean 接口,实现该接口的bean,在创建bean时设置属性后,会调用他的public void afterPropertiesSet() throws Exception
给出一个bean的例子:
package bean;
import java.io.Serializable;
import org.hibernate.event.Initializable;
import org.springframework.beans.factory.InitializingBean;
/**
*
* @author zwc
*
*/
@SuppressWarnings("serial")
public class User implements Serializable ,InitializingBean{
private int id;
private String name;
private int sex;
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;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public User(){ 【一】
}
public User(String name,Integer sex){ 【一】
this.id = 1;
this.name = name;
this.sex = sex;
}
public void init(){ 【二】
this.id = 10101;
this.name = "zwc_init";
this.sex = 1;
}
public void afterPropertiesSet() throws Exception { 【三】
this.id = 10101;
this.name = "zwc_implements_InitializingBean";
this.sex = 1;
}
}