给bean赋值的四种方法

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;

}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值