Spring是一种轻量级的、开源的JavaEE应用软件框架,框架的主要优势之一就是其分层架构,允许选择使用哪一个组件。
Spring的核心是控制反转(IoC:Inversion of Control)和面向切面(AOP:Aspect Oriented Programming).
Spring的优点:
- 方便解耦,简化开发(高内聚低耦合):Spring就是一个大工厂(容器),可以将所有对象创建和依赖关系维护,交给Spring管理;Spring工厂是用于生成bean。
- AOP编程的支持:可以方便的实现对程序进行权限拦截、运行监控等功能。
- 声明式事务的支持:只需要通过配置就可以完成对事务的管理,而无需手动编程。
- 方便程序的测试:Spring对Junit4支持,可以通过注解方便的测试Spring程序。
- 方便集成各种优秀框架:例如对Struts、Hibernate、MyBatis、Quartz等的直接支持
- 降低JavaEE API的使用难度
(一)搭建Spring环境
- 下载Spring
- 安装Springsource-tool-suite插件
(二)开发过程
- 根据业务要求创建实体类或给出接口的实现
- 利用所创建的类,在配置文件中配置Bean信息
- 创建Spring容器(该容器与配置文件相关联——读取配置信息)
- 从容器中获取实例对象,由对象调用方法完成所需要的业务处理
(三)案例
eg1:简单案例(利用构造器注入方式——bean)
//1.实体类
package entity;
public class Computer { //电脑类
private String cpu; //大脑
private String hdd; //硬盘
private String mainborder; //主板
public void setCpu(String cpu) {
this.cpu = cpu;
}
public void setHdd(String hdd) {
this.hdd = hdd;
}
public void setMainborder(String mainborder) {
this.mainborder = mainborder;
}
@Override
public String toString() {
return "Computer [cpu=" + cpu + ", hdd=" + hdd + ", mainborder=" + mainborder + "]";
}
}
//2. 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:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 构造器注入,创建对象. 类名class=包名.类名-->
<bean id="cal" class="java.util.GregorianCalendar"></bean> <!--引用系统类-->
<bean id="com" class="entity.Computer">
<!-- 给对象的变量赋值的方式是set注入(用set函数) -->
<!-- property的name属性值与set方法有关,即set方法名首字母小写 -->
<property name="cpu" value="英特尔" ></property> <!-- 该name的set函数是setCpu,所以name只用小写的cpu即可。 -->
<property name="hdd" value="西数" ></property>
</bean>
</beans>
//3. 测试类(用JUnit4进行测试)
package controller;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringIOC {
ApplicationContext ac;
@Before
public void bf(){
ac=new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test01(){
Object obj=ac.getBean("cal");
System.out.println(obj);
}
@Test
public void test03(){
Object obj=ac.getBean("com");
System.out.println(obj);
}
//执行过程:在new applicationContext时创建容器,容器加载xml文件来创建对象,由getBean(id)匹配xml文件中相应的id取对象。
}
运行结果:
eg2:简单案例(采用注解方式创建Studnet对象和Computer对象,并使用@Resource和@Value注入值显示)
1. Computer.java
package com.albb.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component //相当于<bean id="computer"(默认类名小写) class="controller.Computer">
public class Computer {
@Value("xiaomi") //配置单个属性的值
private String cpu;
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
@Override
public String toString() {
return "Computer [cpu=" + cpu + "]";
}
}
2. Student.java
package com.albb.entity;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.albb.controller.Computer;
@Component("stu") //可修改id值,相当于<bean id="stu" class="entity.Student">
public class Student {
@Value("flora")
private String name;
@Resource(name="computer") //相当于为引用对象赋值,name值为Computer对象的id值
private Computer com;
public Computer getCom() {
return com;
}
public void setCom(Computer com) {
this.com = com;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + ", com=" + com + "]";
}
}
3. 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:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 告诉框架去扫描包中含注解的类 -->
<!-- 如果扫描的包太多,可以给所有的包起个公共的包头名,只写公共头部分即可 -->
<context:component-scan base-package="com.albb"></context:component-scan>
</beans>
4. testSpring.java
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.albb.controller.Computer;
import com.albb.entity.Student;
public class TestSpring {
@Test
public void test01(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Computer com=(Computer)ac.getBean("computer");
System.out.println(com);
}
@Test
public void test02(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu=(Student)ac.getBean("stu");
System.out.println(stu);
}
}
运行结果:
eg3:利用Spring框架的IoC思想,设计Java程序实现控制台的学生信息显示
(1)创建Java工程,导入必需的jar包
(2)创建实体类:HelloBean.java,该类用于描述学生信息
package com.edu;
public class HelloBean {
private String studentName;// 学生姓名
private String course;// 选课课程名
private Double score;// 课程成绩
public HelloBean() {
}
public HelloBean(String studentName, String course, Double score) {
this.studentName = studentName;
this.course = course;
this.score = score;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
(3)创建配置文件hellobean.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">
<bean name="stu1" class="com.edu.HelloBean">
<property name="studentName" value="张三"></property>
<property name="course" value="数学"></property>
<property name="score" value="95"></property>
</bean>
<bean name="stu2" class="com.edu.HelloBean">
<property name="studentName" value="李四"></property>
<property name="course" value="物理"></property>
<property name="score" value="88"></property>
</bean>
<bean name="stu3" class="com.edu.HelloBean">
<property name="studentName" value="王五"></property>
<property name="course" value="计算机"></property>
<property name="score" value="90"></property>
</bean>
</beans>
(4)设计主方法,完成Spring容器的实例化及业务处理——显示3名学生的信息
package com.edu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// (1)创建一个容器实例(与配置文件关联)
ApplicationContext act = new ClassPathXmlApplicationContext(
"hellobean.xml");
// (2)只声明一个对象
HelloBean student;
// (3)从实例容器act中,分别获取3个学生对象,并显示信息
student = (HelloBean) act.getBean("stu1");
System.out.println("姓名:" + student.getStudentName() + " 课程名:"
+ student.getCourse() + " 成绩:" + student.getScore());
student = (HelloBean) act.getBean("stu2");
System.out.println("姓名:" + student.getStudentName() + " 课程名:"
+ student.getCourse() + " 成绩:" + student.getScore());
student = (HelloBean) act.getBean("stu3");
System.out.println("姓名:" + student.getStudentName() + " 课程名:"
+ student.getCourse() + " 成绩:" + student.getScore());
}
}
(2)设计web工程,利用网页显示学生信息
(1)创建web工程,导jar包
(2)创建实体类HelloBean.java,与上面代码相同
(3)创建配置文件hellobean.xml,与上面代码相同
(4)实例化Spring容器:在web.xml中配置Spring容器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring_2_web_helloword</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:hellobean.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
(5)设计网页:采用脚本代码,获取Spring容器,从容器内获取对象并显示
<%@page import="com.edu.HelloBean"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// (1)首先通过request对象,获取web服务器容器
ServletContext sc=request.getServletContext();
//(2)利用Spring框架提供ServletContext的静态方法,从Web服务器中获取 Spring容器
WebApplicationContext wact =WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
// (3)只声明一个对象
HelloBean student;
// (4)从实例容器act中,分别获取3个学生对象,并显示信息
student = (HelloBean) wact.getBean("stu1");
//(5)利用Jsp脚本获取数据并显示
%>
姓名:<%=student.getStudentName()%><br>
课程名:<%=student.getCourse()%><br>
成绩:<%=student.getScore()%><br>
--------------------------------------<br>
<%student = (HelloBean) wact.getBean("stu2"); %>
姓名:<%=student.getStudentName()%><br>
课程名:<%=student.getCourse()%><br>
成绩:<%=student.getScore()%><br>
--------------------------------------<br>
<%student = (HelloBean) wact.getBean("stu3"); %>
姓名:<%=student.getStudentName()%><br>
课程名:<%=student.getCourse()%><br>
成绩:<%=student.getScore()%><br>
--------------------------------------
</body>
</html>