一.Spring是什么?
Rod Johnson:SpringFramework创始人,音乐学博士
技术主张:技术以实用为本
Spring取名“春天”之意,意在表示javaEE的春天。它是轻量级框架,是当前的主流框架。它的目标是使现有技术更加易用,推进编码最佳实践。
1、Spring的核心是一个轻量级(Lightweight)的容器(Container)。
2、Spring是实现IoC(Inversion of Control)容器和非入侵性(No intrusive)的框架。
3、Spring提供AOP(Aspect-oriented programming)概念的实现方式。
4、Spring提供对持久层(Persistence)、事务(Transcation)的支持。
5、Spring提供MVC Web框架的实现,并对一些常用的企业服务API(Application Interface)提供一致的模型封装。
6、Spring提供了对现存的各种框架(Struts2、JSF、Hibernate、Mybatis)相整合的方案。
总之,Spring框架是一个全方位、一站式的应用程序框架。
二.为什么要使用Spring框架?
图片作者:唐小娟
在考虑一个框架时,你需要考虑的问题通常有这么几个:
- 它能带给我什么?
- 我使用的语言和平台支持这个框架吗?
- 这个框架和其他我正在使用的框架的兼容性怎么样?
- 它的开发效率如何?
- 安全性如何?
- 方便进行单元测试吗?
- 这个框架的文档支持怎么样?社区够活跃吗?
而Spring实现了IOC,实现了AOP,同时提供了事务管理和MVC框架的实现。它完全使用Java语言,不需要再学习新的语言,另外Spring同其他框架的兼容性、可扩展性都非常好,更重要的是强大的文档支持和活跃的社区,这些是为什么使用Spring的原因。
三.Spring资源的获取
四.如何使用Spring进行项目开发?入门例子示范
- 新建项目,添加Spring相关的jar包
- 创建实体类
public class HelloWorld {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
//输出消息内容
public void printMsg(){
System.out.println(this.getMessage());
}
}
3.在src下添加Spring的配置文件:applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="helloWorld" class="com.bw.bean.HelloWorld">
<property name="message" value="Hello Spring!"/>
</bean>
</beans>
4.编写测试程序
public class Test {
public static void main(String[] args) {
//通过ClassPathXmlApplicationContext实例化Spring的上下文
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过ApplicationContext的getBean方法,根据id获取bean的实例
HelloWorld hw = (HelloWorld) context.getBean("helloWorld");
//执行打印方法
hw.printMsg();
}
}
好了,通过这个小例子,我们已经入门了,接下来,就可以学习Spring框架的核心特性:IOC和AOP了。