一、Spring是什么?
1.Spring描述
- Spring是一个开源框架
- Spring为简化企业级应用开发而生,使用Spring可以使简单的JavaBean实现以前只有EJB才能实现的功能
- Spring是一个IoC(DI)和AOP容器框架
2.Spring的具体描述:
- 轻量级:Spring使非侵入性的。基于Spring开发的应用中的对象可以不依赖与Spring的API
- 依赖注入:(DI — dependency injection、IOC)
- 面向切面编程:(AOP—aspect oriented programming)
- 容器:Spring是一个容器,因为它包含并且管理应用对象的生命周期
- 框架:Spring实现了使用简单的组件配置组合成一个复杂的应用,在Spring中可以使用XML和Java注解组合这些对象
- 一站式:在IoC和AOP的基础上可以整合各种企业应用开发的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的SpringMVC和持久层的Spring JDBC)
3.Spring模块
4.Spring开发环境搭建
- 如果使用Eclipse作为开发环境,需要安装Spring-tool-suite插件。下载地址:https://spring.io/tools
- 使用IDEA作为开发工具,不需要安装插件,可以直接新建Spring项目。
5.Spring之HelloWorld
-
首先需要导入一些 Spring 所依赖的 jar 包
commons-logging-1.1.3.jar spring-beans-4.0.0.RELEASE.jar spring-context-4.0.0.RELEASE.jar spring-core-4.0.0.RELEASE.jar spring-expression-4.0.0.RELEASE.jar
-
新建 HelloWorld 类
package com.spring.HelloWorld; public class HelloWorld { private String name; public void setName(String name) { System.out.println("setName:" + name); this.name = name; } public void hello() { System.out.println("hello:" + name); } public HelloWorld() { System.out.println("HelloWorld's Constructor..."); } }
-
新建Main类
package com.spring.HelloWorld; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { /* // 创建 HelloWorld 的一个对象 HelloWorld helloWorld = new HelloWorld(); // 为 name 属性赋值 helloWorld.setName("yangqi"); */ // 1.创建 Spring 的 IoC 对象 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 2.从 IoC 容器中获取 Bean 实例 HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); // 调用 hello() 方法 helloWorld.hello(); } }
-
新建applicationContext.xml文件(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 --> <bean id="helloWorld" class="com.spring.HelloWorld.HelloWorld"> <property name="name" value="yangqi"></property> </bean> </beans>