Class cls = Class.forName(
"com.raykey.beans.User"
);
Method mtd = cls.getMethod(
"setName"
,
new
Class[]{String.
class
});
Object obj = (Object)cls.newInstance();
mtd.invoke(obj,
new
Object[]{
"Erica"
});
return obj;
|
Object obj = Class.forName(
"com.raykey.beans.User"
).newInstance();
BeanWrapper
bw =
new
BeanWrapperImpl(obj);
bw.setPropertyValue(
"name"
,
"Erica"
);
System.out.println(
"User name=>"
+bw.getPropertyValue(
"name"
));
|
<
beans
>
<
description
>
Spring Bean Configuration Sample
</
description
>
<
bean
id
=
"TheAction"
⑴
class
=
"com.raykey.spring.qs.UpperAction"
⑵
singleton
=
"true"
⑶
init-method
=
"init"
⑷
destroy-method
=
"cleanup"
⑸
depends-on
=
"ActionManager"
⑹
>
<
property
name
=
"message"
>
<
value
>
HeLLo
</
value
>
⑺
</
property
>
<
property
name
=
"desc"
>
<
null
/>
</
property
>
<
property
name
=
"dataSource"
>
<
ref
local
=
"dataSource"
/>
⑻
</
property
>
</
bean
>
<
bean
id
=
"dataSource"
class
=
"org.springframework.jndi.JndiObjectFactoryBean"
>
<
property
name
=
"jndiName"
>
<
value
>
java:comp/env/jdbc/sample
</
value
>
</
property
>
</
bean
>
</
beans
>
|
InputStream is =
new
FileInputStream(
"bean.xml"
);
XmlBeanFactory factory =
new
XmlBeanFactory(is);
Action action = (Action) factory.getBean(
"TheAction"
);
|
相对BeanFactory而言,ApplicationContext提供了以下扩展功能:
1
. 资源访问
提供取得资源文件更方便的方法,支持对文件和URL的访问。
2
. 消息解析
提供文字消息解析的方法。
3
. 国际化支持
我们可以在Beans.xml文件中,对程序中的语言信息(如提示信息)进行定义,将程序中的提示信息抽取到配置文件中加以定义,为我们进行应用的各语言版本转换提供了极大的灵活性。
4
. 事件的监听与传播
事件传播特性为系统中状态改变时的检测提供了良好支持。ApplicationContext可以发布事件,对事件感兴趣的Bean可以接收到这些事件。
5
. 多实例加载
可以在同一个应用中加载多个Context实例。
|
public void
testQuickStart() {
ApplicationContext ctx=
new
FileSystemXmlApplicationContext(
"bean.xml"
);
Action action = (Action) ctx.getBean(
"TheAction"
);
System.out.println(action.execute(
"Rod Johnson"
));
}
|
public
class
HelloBean {
private
String
helloWord
;
private
Date
date
;
public
void
setHelloWord(String helloWord) {
this
.
helloWord
= helloWord;
}
public
String getHelloWord() {
return
helloWord
;
}
public
void
setDate(Date date) {
this
.
date
= date;
}
public
Date getDate() {
return
date
;
}
}
|
<
beans
>
<
bean
id
=
"dateBean"
class
=
"java.util.Date"
/>
<
bean
id
=
"helloBean"
class
=
"onlyfun.caterpillar.HelloBean"
autowire
=
"byType"
>
<
property
name
=
"helloWord"
>
<
value
>
Hello!
</
value
>
</
property
>
</
bean
>
</
beans
>
|
<
beans
>
<
bean
id
=
"date"
class
=
"java.util.Date"
/>
<
bean
id
=
"helloBean"
class
=
"onlyfun.caterpillar.HelloBean"
autowire
=
"byName"
>
<
property
name
=
"helloWord"
>
<
value
>
Hello!
</
value
>
</
property
>
</
bean
>
</
beans
>
|
public
class
SomeBean {
private
String[]
someStrArray
;
private
Some[]
someObjArray
;
private
List
someList
;
private
Map
someMap
;
//getter and setter
}
|
public
class
Some {
private
String
name
;
public
String getName() {
return
name
;
}
public
void
setName(String name) {
this
.
name
= name;
}
public
String toString() {
return
name
;
}
}
|