官网:http://spring.io
现在官网好像都没有直接提供Spring压缩包下载的地址了,推荐使用Maven工具来构建Spring项目。
后来看了下Spring的reference文档,里面有压缩包的下载链接,不过下载速度比较慢,不想使用Mavne的朋友可以去下载。
http://repo.spring.io/release/org/springframework/spring
进入官网,点击Projects菜单,Spring里面包含了很多项目,因为我们只是使用Spring最简单的功能,选择Spring Framework,可以找到Spring的Maven依赖。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
依赖进来的jar包有下面7个,直接下载压缩包的朋友可以把对应的jar包加入到项目中。
spring-core-4.1.4.RELEASE.jar
spring-beans-4.1.4.RELEASE.jar
spring-context-4.1.4.RELEASE.jar
spring-aop-4.1.4.RELEASE.jar
spring-expression-4.1.4.RELEASE.jar
commons-logging-1.2.jar
aopalliance-1.0.jar
1、在Eclipse中新建Maven项目,在pom.xml文件中加入Spring的依赖。
2、新建服务类HelloService
package com.lnc.hello.spring;
public class HelloService {
public void hello() {
System.out.println("Hello Spring");
}
}
3、在项目的src/main/resources目录下新建Spring配置文件beans.xml,并把HelloService配置成Spring中的Bean,这样HelloService就受Spring管理了。
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="helloBean" class="com.lnc.hello.spring.HelloService" />
</beans>
4、新建测试类HelloMain
package com.lnc.hello.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml");
HelloService helloService = context.getBean(HelloService.class);
helloService.hello();
}
}
5、运行主函数,控制台输出Hello Spring。
代码中的context会报提示:
Resource leak: 'context' is never closed
这是因为读beans.xml配置的文件流没有正常关闭,加下面代码关闭即可。
((ClassPathXmlApplicationContext) context).close();