分为定义,初始化,使用,消亡
写个例子测试一下:
第一步:建一个类User,代码如下:
package
test.lyx;
public
class
User {
private
String
userName
;
public
String getUserName() {
return
userName
;
}
public
void
setUserName(String userName) {
this
.
userName
= userName;
}
}
第二步:将
User
注入.
applicationContext.xml
配置如下:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<!
DOCTYPE
beans
PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
<
beans
>
<
bean
id
=
"user"
class
=
"test.lyx.User"
abstract
=
"false"
singleton
=
"true"
lazy-init
=
"default"
autowire
=
"byType"
dependency-check
=
"default"
>
<
property
name
=
"userName"
>
<
value
>
liuyuanxi
</
value
>
</
property
>
</
bean
>
</
beans
>
第三步:建一个类
TestMain
测试一下:
package
test.lyx;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.FileSystemXmlApplicationContext;
public
class
TestMain {
public
static
void
main(String[] args) {
ApplicationContext context=
new
FileSystemXmlApplicationContext(
"test/lyx/applicationContext.xml"
);
User user1=(User)context.getBean(
"user"
);
System.
out
.println(user1.getUserName());
}
}
这样运行该类会打出
liuyuanxi
.那么这几步就是
bean
的定义和使用.
接下来我们在
User
类中加上两个方法:
init clear,
当然方法明任你起.
public
void
init(){
this
.
userName
=
"zhangsan"
;
}
public
void
clear(){
this
.
userName
=
null
;
}
然后将配置文件修改如下:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<!
DOCTYPE
beans
PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
<
beans
>
<
bean
id
=
"user"
class
=
"test.lyx.User"
abstract
=
"false"
singleton
=
"true"
lazy-init
=
"default"
autowire
=
"byType"
dependency-check
=
"default"
init-method="init" destroy-method="clear"
>
<
property
name
=
"userName"
>
<
value
>
liuyuanxi
</
value
>
</
property
>
</
bean
>
</
beans
>
这里面的红线部分就是修改的内容.如果
init-method
属性设置了方法,那么就会在
bean
初始化的时候被执行.而
destroy-method
在消毁之前执行.
第二种方法:(实现初始化,和消毁的两个接口)
可以不在配置文件中指定
init-method
,
destroy-method
两个方法.
我们把
User
类修改一下:代码如下:
package
test.lyx;
import
org.springframework.beans.factory.InitializingBean;
import
org.springframework.beans.factory.DisposableBean;
public
class
User
implements
InitializingBean,DisposableBean{
private
String
userName
;
public
String getUserName() {
return
userName
;
}
public
void
setUserName(String userName) {
this
.
userName
= userName;
}
public
void
init(){
this
.
userName
=
"zhangsan"
;
}
public
void
clear(){
this
.
userName
=
null
;
}
public
void
afterPropertiesSet()
throws
Exception {
this
.
userName
=
"wangwu"
;
//
TODO
Auto-generated method stub
}
public
void
destroy()
throws
Exception {
this
.
userName
=
null
;
//
TODO
Auto-generated method stub
}
}
修改过后的类,就是在原来的基础上,实现两个接口
InitializingBean,DisposableBean
也就是初始化和消毁的接口,这里我们要把
InitializingBean
接口里的
afterPropertiesSet
方法给覆盖掉,也就是将初始化的东西写在这个方法以里面.同时也要把
DisposableBean
接口的
destroy
方法覆盖掉,
消毁的东西写在这个方法里.这样的话,就无需在配置文件中配置
init-method
和
destroy-method
两个方法.
整个的过程就是
bean
的生命周期.