关于Spring的介绍参考百度百科:
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
官方网站:http://spring.io/
最新开发包及文档下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/
Spring的核心思想:IOC 控制反转;AOP 面向切面;
一、Spring之HelloWorld实现
1.新建一个JavaProject:Spring401;
2.添加jar包:下载Spring开发包,并解压缩:这里使用的是4.0.6版本
libs里面是Spring的所有jar包,这些jar包包括文档和源码。虽然里面有很多jar包,最常用的核心包有一下几个:
在工程根目录下新建一个spring文件夹,把这几个核心包复制进去并添加到工程中:
Spring功能之一是能够管理bean,管理实例,以单例形式管理。
3.新建HelloWorld类:
package com.test.service;
public class HelloWorld {
public void say(){
System.out.println("你好,Spring4");
}
}
4.添加spring的配置文件beans.xml(文件名字随意)
<?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">
</beans>
下面使用Spring的方式新建一个HelloWorld类的对象:
<?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="helloWorld" class="com.test.service.HelloWorld"></bean>
</beans>
这样就通过Spring的方式新建了一个HelloWorld类的对象,通过id属性就能够使用这个对象。
新建一个测试方法:
package com.test.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.service.HelloWorld;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld hw = (HelloWorld) ac.getBean("helloWorld");
hw.say();
}
}
这里首先通过ClassPathXmlApplicationContext("beans.xml")来加载Spring的配置文件,返回的是一个ApplicationContext的对象。接着通过这个对象的getBean方法来获取Spring定义的对象。
这里是Spring的一个管理实例对象的功能。