新浪博客

ClassPathXmlApplicationContext启动spring容器

2018-05-27 00:35阅读:
对于spring初学者如果想了解spring,那么最简单的方式就是先了解spring容器的启动方式,然后再去深入研究容器的启动过程和原理。 下面介绍一下spring容器启动最简单的方式——ClassPathXmlApplicationContext。


1. spring容器jar包引入
maven坐标dependency
groupId:org.springframework
artifactId:spring-context
version:4.3.11.RELEASE


2. 定义一个接口类
package com.aa.test;
public interface HelloApi {
void sayHello();
}
3. 定义一个实现类
package com.aa.test;
public class HelloApiImpl implements HelloApi {
@Override
public void sayHello() {
System.out.println('Hello World');
}
}
4. 新建xml配置文件
需要在resources目录下创建一个配置文件,文件名没有特别要求,例如本文就用helloworld.xml
bean配置:bean id='helloApi' class='com.aa.test.HelloApiImpl'


5. 定义启动文件
package com.aa.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloApiTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext('helloworld.xml');
HelloApi helloApi = context.getBean('helloApi', HelloApi.class);
helloApi.sayHello();
}
}
通过上面简单的例子就可以通过ClassPathXmlApplicationContext启动spring容器了,是不是很简单。

我的更多文章

下载客户端阅读体验更佳

APP专享