由于spring官方的例子都是用maven进行代码管理, 我打算以后的代码也用maven进行管理。
spring一个重要的优点就是Ioc,也就是控制反转,可以用xml文件来生成类的实例。我以前都是用eclipse下的tomcat方式来管理bean实例,用spring自带的spring tool suits管理还有点不习惯,不过生产工具都是不断优化的,所以这里也学着习惯使用。
配置文件可以放在resources文件夹下,具体目录为src\main\resources,src下的另一个文件是java文件,如图
其中的applicationContext.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"
>
<!-- Beans Declaration -->
<
bean
id
=
"TestTask"
class
=
"com.otv.task.TestTask"
></
bean
>
<
bean
id
=
"ThreadPoolMonitorService"
class
=
"com.otv.monitor.srv.ThreadPoolMonitorService"
>
<
property
name
=
"monitoringPeriod"
value
=
"5"
/>
</
bean
>
<
bean
id
=
"TestRejectedExecutionHandler"
class
=
"com.otv.handler.TestRejectedExecutionHandler"
></
bean
>
<
bean
id
=
"TestThreadPoolExecutorService"
class
=
"com.otv.srv.TestThreadPoolExecutorService"
>
<
property
name
=
"corePoolSize"
value
=
"1"
/>
<
property
name
=
"maxPoolSize"
value
=
"3"
/>
<
property
name
=
"keepAliveTime"
value
=
"10"
/>
<
property
name
=
"queueCapacity"
value
=
"3"
/>
<
property
name
=
"testRejectedExecutionHandler"
ref
=
"TestRejectedExecutionHandler"
/>
</
bean
>
<
bean
id
=
"Starter"
class
=
"com.otv.start.Starter"
>
<
property
name
=
"threadPoolMonitorService"
ref
=
"ThreadPoolMonitorService"
/>
<
property
name
=
"testThreadPoolExecutorService"
ref
=
"TestThreadPoolExecutorService"
/>
</
bean
>
</
beans
>
然后说一下如何加载这个xml文件,通常是用一个
Application类,
是具体为什么叫这个名字,我还是不确定,我发现许多项目都是叫这个名字,这里我也跟着叫这个名字,其中的代码为
public
class
Application {
public
static
void
main(String[]
args
) {
ApplicationContext
context
=
new
ClassPathXmlApplicationContext(
"applicationContext.xml"
);
Starter
starter
= (Starter)
context
.getBean(
"Starter"
);
starter
.start();
}
}
这样我们就可以把xml文件加载进来,希望获得
Starter
这个实例,就可以使用上面的方法。
这里有一个小例子关于线程池的,顺带着学一下线程池的知识。