第1章.Spring概述

Spring概述

The Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications.

特点:轻量级、一站式、开发框架

历史:

2002 Rod Johnson, Apache 2.0 License 初始版, an idea of Spring came out due to the bad efficiency and performance of (EJB) Enterprise Java Beans.

(Btw, JavaEE is as good as Spring nowadays)

2004 版本1.0,核心功能

2006 版本2.0 AOP提升

2007 版本2.5 支持Annotation

2009 版本3.0 功能更新

2013 版本4.0 Java 8支持

Spring核心技术:

IoC (Inversion of Control 控制反转):

类比:形形色色的螺丝刀:开始可能只使用一种一字刀口的就可以,但随着业务增多,可能需要的种类越来越多,需要带几十把螺丝刀-->改进成螺丝刀套装

控制的是刀口的形状;IoC之前:制造商来控制(制造了什么就得用什么);IoC之后:使用者来控制选择螺丝刀头

public class ScrewDriver {
private Header header = new StraightHeader(); public void use() {
Syso("Use straight screw driver");
}
}

ScrewDriver依赖于StraightHeader,并且直接创建StraightHeader对象(创建的是什么对象就只能使用什么)

如果要使用十字刀,则需要修改ScrewDriver类后重新编译:

public class ScrewDriver {
private Header header = new CrossHeader(); public void use() {
Syso("Use cross screw driver");
}

从设计模式来看,耦合了具体的实现而不是接口

--> 创建的时候可以使用螺丝刀头的接口

public class ScrewDriver {
private Header header; public ScrewDriver (Header header) {
this.header = header;
} public void use() {
Syso("Use " + header.type() + " screw driver");
}
}

控制什么?控制的是对象之间的依赖关系:创建时,把依赖的对象(刀头)注入到螺丝刀对象中 -- Dependency Injection (DI 依赖注入)

谁来控制?IoC之前:对象的提供者

IoC之后:IoC容器,使用者通过配置文件告诉IoC容器需要用到什么对象,IoC将对线创建并组合成最终可用的对象

DI是IoC的目标,IoC是DI的实现方式。

Non-IoC verse IoC:

AOP (Aspect-Oriented Programming 面向切面编程)

目标:实现业务逻辑与非业务逻辑分离

Case: 计算器

逻辑:

public class Calculator {
public int add(int a, int b) {
return a + b;
}
}

加入日志(函数入口出口、异常):

public class Calculator {
private static final Logger logger = Logger.getLogger(Calculator.class); public int add(int a, int b) {
logger.info("Enter into Calculator.add(a,b) method"); int result = 0;
try {
result = a + b;
} catch (Exception ex {
logger.info("Exception in Calculator.add(a,b) method");
}
logger.info("Leaving Calculator.add(a,b) method"); return result;
}
}

可以看到,核心代码只有一行 result = a + b; 但是需要很多代码来实现日志部分。

如果有很多业务 (比如减法)需要使用到日志功能呢?

--> 业务逻辑 与 非业务逻辑 分开:提高可维护性

public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
} public class MyLogger {
private static final Logger logger = Logger.getLogger(MyLogger.class);
public void methodEnter (Method method) {
logger.info("Enter into " + method.getMethodInfo() + " method");
}
public void methodException (Method method) {
logger.info("Exception in " + method.getMethodInfo() + " method");
}
public void methodLeave (Method method) {
logger.info("Leaving " + method.getMethodInfo() + " method");
}
}

Spring框架提供的模块:

IoC容器--Core Container:对象创建、装配;生命周期管理;上下文环境

AOP;支持AspectJ;/Instrumentation/Messaging(这里不讲)

Data Access 数据访问:

提供JDBC支持,Spring可以将JDBC (连接管理/异常处理等)这些逻辑封装后方便地直接取得访问返回的数据结果

事务管理:Transactions

ORM整合:比如可以整合MyBatis等

OXM/JMS(这里不讲)

Web框架:

提供了基于Servlet的MVC框架

常用Web工具支持

模板支持

Spring其他项目:

Spring包含了很多子项目,Spring framework只是其中一个子项目

比如支持安卓、支持云计算、支持大数据等的框架

https://spring.io/projects

Why Spring framework?

提供方便的开发工具:比如JDBC开发等

整合了常用框架:比如MyBatis

提高了开发者的开发效率

HelloWorld示例:

Eclipse JavaEE中,新建Maven工程

勾选Create a simple project (skip archetype selection)

生成符合Maven规范的目录结构

报错:

1. Maven Java EE configuration Problems (1 item) -> web.xml is missing and <failOnMissingWebXML> is set to true

解决:右键项目,Java EE Tools -> Generate Deployment Descriptor Stub

自动在src/main/webapp/下生成了WEB-INF/web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
<display-name>spring-web</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

2. Java Build Path Problems (1 item) -> Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.

解决:调整jdk版本:右键项目->Properties->Project Facets->Java->1.7

将写好的index.html文件放置于webapp目录下

对项目添加Tomcat服务:

Servers,添加Server->Tomcat

Run as -> Run on server

http://localhost:8080/spring-web/ 页面出现index.html内容

Spring上下文环境的配置文件:

src/main/resources/application-context.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:p="http://www.springframework.org/schema/p"
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">
</beans> 

刚才的web.xml中写入配置:(<welcome-file-list>之后)

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:application-context.xml </param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>

<listener>中的ContextLoaderListener:在Spring开始的时候到classpath:application-context.xml中加载环境的上下文配置

<servlet>中的DispatcherServlet:Spring中Servlet的入口 (对应servlet文件)

在WEB-INF下添加example-servlet.xml (因为servlet-name为example,需要符合servlet命名规则:在servletname后加上"-servlet")

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.netease.nanodegree.web.controller" />
</beans> 

能看到这里的配置只有一个:<context:component-scan base-package="com.netease.course.web.controller"/>

表示在这个包下搜索组件

创建Spring MVC中的Controller:

src/main/java -> New Java Class named HelloController.java -> package: com.netease.nanodegree.web.controller

package com.netease.nanodegree.web.controller;

@Controller
@RequestMapping(value = "/hello")
public class HelloController { @RequestMapping(value = "/spring")
public void spring(HttpServletResponse response) throws IOException {
response.getWriter().write("Hello, Spring Web!");
}
}

需要在spring-web/pom.xml中添加相应的依赖

<dependencies>
<dependency>
<!-- servlet的依赖 -->
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency> <dependency>
<!-- Spring的依赖 -->
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
</dependencies>

Run on server:

http://localhost:8080/spring-web/api/hello/spring

那么,Spring是怎么提高web开发效率的呢?

在上例中不是很明显,但是如果有很多接口呢?

直接使用Servlet的话,需要设置很多Servlet,每个Servlet都要配置属性;

通过Spring MVC的话,只需要配置Servlet的入口,其他的都可以进行管理

Java开发工程师(Web方向) - 04.Spring框架 - 第1章.Spring概述的更多相关文章

  1. Java开发工程师(Web方向) - 04.Spring框架 - 第2章.IoC容器

    第2章.IoC容器 IoC容器概述 abstract: 介绍IoC和bean的用处和使用 IoC容器处于整个Spring框架中比较核心的位置:Core Container: Beans, Core, ...

  2. Java开发工程师(Web方向) - 04.Spring框架 - 期末测试

    Spring框架客观题 Spring框架编程题 http://blog.csdn.net/sinoacc/article/details/51702458 1 (25分) 假设有如下数据表: crea ...

  3. Java开发工程师(Web方向) - 04.Spring框架 - 第3章.AOP技术

    第3章--AOP技术 Spring框架 - AOP概述 笔记https://my.oschina.net/hava/blog/758873Spring框架 - AOP使用 笔记https://my.o ...

  4. Java开发工程师(Web方向) - 04.Spring框架 - 第5章.Web框架

    第5章--Web框架 Web框架概述 Web框架单元测验 本次得分为:13.50/15.00, 本次测试的提交时间为:2017-09-25 1单选(2分) 关于Spring MVC中Dispatche ...

  5. Java开发工程师(Web方向) - 04.Spring框架 - 第4章.数据访问

    第4章--数据访问 Spring JDBC DAO (Data Access Object) 实现数据访问相关接口(接口和实现分离) ORM (Object Relation Mapping) 对象关 ...

  6. Java开发工程师(Web方向) - 02.Servlet技术 - 第3章.Servlet应用

    第3章.Servlet应用 转发与重定向 转发:浏览器发送资源请求到ServletA后,ServletA传递请求给ServletB,ServletB生成响应后返回给浏览器. 请求转发:forward: ...

  7. Java开发工程师(Web方向) - 02.Servlet技术 - 第4章.JSP

    第4章--JSP JSP JSP(Java Server Pages) - 中文名:Java服务器页面 动态网页技术标准 JSP = Html + Java + JSP tags 在服务器端执行,返回 ...

  8. Java开发工程师(Web方向) - 02.Servlet技术 - 第2章.Cookie与Session

    第2章--Cookie与Session Cookie与Session 浏览器输入地址--HTTP请求--Servlet--HTTP响应--浏览器接收 会话(session):打开浏览器,打开一系列页面 ...

  9. Java开发工程师(Web方向) - 02.Servlet技术 - 第1章.Servlet

    第1章--Servlet Servlet简介 Servlet应用于? 浏览器发出HTTP请求,服务器接收请求后返回响应给浏览器. 接收请求后到返回响应之间: 服务器将请求对象转交给Servlet容器 ...

随机推荐

  1. C#中Form的Paint事件响应方法与重载虚方法OnPaint()的区别

    Form_Paint()方法是Paint事件的响应方法,OnPaint是可重载的虚方法,OnPaint方法是调用Paint事件的,用哪一个,效果是一样,就看那一个方便了内部是这样实现的: protec ...

  2. github commit 报错:error: failed to push some refs to 'https:'错误解决方法

    为什么会出现这个问题呢? 因为我在github中删除了一个文件readme.txt,但是本地并不知道我删除了readme.txt,本地中还保存了readme.txt文件,导致了云端的文件,和本地的文件 ...

  3. [转]TestNG的多线程并行

    前言 最近在做项目里的自动化测试工作,使用的是TestNG测试框架,主要涉及的测试类型有接口测试以及基于业务实际场景的场景化测试.由于涉及的场景大多都是大数据的作业开发及执行(如MapReduce.S ...

  4. MATLAB PCHIP函数一阶求导分析

    MATLAB PCHIP函数一阶求导分析 摘要:本文首先根据三次立方插值的一般表达式,得出分段三次立方插值时,每个小区间上的各次项系数.分析发现,三次项.二次项.一次项系数都与小区间端点处的一阶导数值 ...

  5. 第26章 FMC—扩展外部SDRAM

    本章参考资料:<STM32F76xxx参考手册2>.<STM32F7xx规格书>.库帮助文档<STM32F779xx_User_Manual.chm>. 关于SDR ...

  6. php导出word格式数据的代码(转)

    本节内容:一个php导出文档的类 例子:<?php /*** 生成word文档的类* by www.jbxue.com*/class word{     function start()    ...

  7. 【前端框架-Vue-基础】$attr及$listeners实现跨多级组件的通信

    父子 A 组件与 B 组件之间的通信: (父子组件) 如上图所示,A.B.C三个组件依次嵌套,按照 Vue 的开发习惯,父子组件通信可以通过以下方式实现: A to B 通过props的方式向子组件传 ...

  8. 简单几行代码使用百度地图API接口分页获取信息

    首发于: 万能助手扩展开发:使用百度地图API接口分页获取信息_电脑计算机编程入门教程自学 http://jianma123.com/viewthread.aardio?threadid=426 使用 ...

  9. About Me - 关于

    0x00 简介 97年生 计算机相关专业,无线电安全攻防方向. 涉猎较多,喜欢研究无线.硬件.软件.网络.攻击.检测.防御等各类安全技术 精通较少,主要擅长的还是硬件.渗透.无线攻击方面. 现阶段在研 ...

  10. python初学者日记01(字符串操作方法)

    时间:2018/12/16 作者:永远的码农(博客园) 环境: win10,pycharm2018,python3.7.1 1.1  基础操作(交互输入输出) input = input(" ...