作者丨geekartt
https://segmentfault.com/a/1190000016773059?utm_source=tag-newest
作为Spring框架,它最主要的功能就是管理一堆使App(应用)发挥功能的类,这些作为整个App的基石、主干的类,就叫做bean。
要管理bean,也即是这堆发挥业务功能的类,就不能直接把它们new出来,这样缺乏统一的调度。所以,Spring使用.xml配置文件作为媒介,以IoC(Inversion of Control 控制反转)作为工具,将这些bean拿给Spring container作统一管理。
基于此,要把一个bean扔给container,至少需要两部分:
bean对应的类的定义
间接控制的.xml配置文件
之所以需要两部分也是容易理解的,首先你得有一个bean自身的定义吧。再来,你得告诉Spring container应该以什么样的方式去接受这个bean,这个就是由.xml文件来说明。
例如,我们要管理的bean叫做HelloWorld,那么它的这两部分分别是:applicationContext-src.xml:
<
beans
xmlns
=
"http://www.springframework.org/schema/beans"
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
=
"
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
<
bean
id
=
"helloWorld"
class
=
"com.terence.HelloWorld"
>
<
property
name
=
"message"
value
=
"Hello Terence's World!"
/>
bean
>
beans
>
和HelloWorld.java:
public
class
HelloWorld
{
private
String message;
public
void
setMessage
(
String message
)
{
this
.message = message;
}
public
void
getMessage
(
)
{
System.
out
.println(
"Your Message : "
+ message);
}
}
有了这两部分,Spring container就可以正确地接收名为HelloWorld的bean。
现在,如果要使用这个bean,当然不可以直接去触碰HelloWorld这个bean,而是需要通过管理它的代理人Spring container来得到bean,进而用这个bean来为自己服务。
例如,名为MainApp.java的这个类,现在需要使用HelloWorld这个bean的服务,我们就可以这样做:
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public
class
MainApp
{
@SuppressWarnings
(
"resource"
)
public
static
void
main
(String[] args)
{
ApplicationContext context =
new
ClassPathXmlApplicationContext(
"applicationContext-src.xml"
);
HelloWorld obj = (HelloWorld) context.getBean(
"helloWorld"
);
obj.getMessage();
}
}
这里有两部分:
首先根据配.xml置文件的位置去拿到Spring container,也即是这里的Context,可以把它理解为几种Spring container中最著名的代言人。
有了这个代言人后,自然就可以向这个代言人索取需要的bean HelloWorld,于是由context.getBean()方法去拿到需要的bean。
这样得到bean后,就可以直接使用了。