Spring框架介绍:
Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。
◆目的:解决企业应用开发的复杂性
◆功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
◆范围:任何Java应用
Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架。
轻量——从大小与开销两方面而言Spring都是轻量的。完整的Spring框架可以在一个大小只有1MB多的JAR文件里发布。并且Spring所需的处理开销也是微不足道的。此外,Spring是非侵入式的:典型地,Spring应用中的对象不依赖于Spring的特定类。
控制反转——Spring通过一种称作控制反转(IoC)的技术促进了松耦合。当应用了IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。你可以认为IoC与JNDI相反——不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。
面向切面——Spring提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。
容器——Spring包含并管理应用对象的配置和生命周期,在这个意义上它是一种容器,你可以配置你的每个bean如何被创建——基于一个可配置原型(prototype),你的bean可以创建一个单独的实例或者每次需要时都生成一个新的实例——以及它们是如何相互关联的。然而,Spring不应该被混同于传统的重量级的EJB容器,它们经常是庞大与笨重的,难以使用。
框架——Spring可以将简单的组件配置、组合成为复杂的应用。在Spring中,应用对象被声明式地组合,典型地是在一个XML文件里。Spring也提供了很多基础功能(事务管理、持久化框架集成等等),将应用逻辑的开发留给了你。
所有Spring的这些特征使你能够编写更干净、更可管理、并且更易于测试的代码。它们也为Spring中的各种模块提供了基础支持。
Spring框架的基本组成:
1、最完善的轻量级核心框架。
2、通用的事务管理抽象层。
3、JDBC抽象层。
4、集成了Toplink, Hibernate, JDO, and iBATIS SQL Maps。
5、AOP功能。
6、灵活的MVC Web应用框架。
Spring框架优点:
1.放便解耦,简单开发
Spring就是一个大工厂,可以将所有对象的创建和依赖关系的维护,交给Spring管理。
2.Aop 编程支持
Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能。
3.声明事务的支持
只需要通过配置就可以完成对事务的管理,而无须手动编程。
4.方便程序的测试
Spring对Junit4支持,可以通过注解方便的测试Spring程序。
5.方便框架的集合
Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts2、Hibernate、MyBatis、Quartz等)的直接支持
6.降低开发难度
Spring对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低。
控制反转(或依赖注入)
控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
案例:实现Spring的IoC
IOC/DI
将以前由程序员实例化对象/赋值的工作交给了spring处理
实现我们导入我们所需要的架包
pom.xml
代码如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dengrenli</groupId>
<artifactId>T226_spring</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>T226_spring Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>T226_spring</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
然后我们先来介绍我们所需要用到的类
UserBiz.java
代码如下:
package com.dengrenli.ioc.biz;
/**
* 通过企业的案例来讲解使用spring ioc的必要性
*
*
* @author Administrator
*
*/
public interface UserBiz {
public void upload(); //上传
}
UserBizImpl.java
代码如下:
package com.dengrenli.ioc.biz.impl;
import com.dengrenli.ioc.biz.UserBiz;
public class UserBizImpl implements UserBiz{
@Override
public void upload() {
System.out.println("实现用户上传的功能");
}
}
UserBizImpl2.java
代码如下:
package com.dengrenli.ioc.biz.impl;
import com.dengrenli.ioc.biz.UserBiz;
public class UserBizImpl2 implements UserBiz{
@Override
public void upload() {
System.out.println("开始优化性能的代码");
System.out.println("实现用户上传的功能");
}
}
OrderAcion.java
代码如下:
package com.dengrenli.ioc.web;
import com.dengrenli.ioc.biz.UserBiz;
import com.dengrenli.ioc.biz.impl.UserBizImpl;
import com.dengrenli.ioc.biz.impl.UserBizImpl2;
public class OrderAcion {
private UserBiz userBiz;
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public void upload() {
userBiz.upload();
}
}
UserAcion.java
代码如下:
package com.dengrenli.ioc.web;
import java.util.List;
import com.dengrenli.ioc.biz.UserBiz;
import com.dengrenli.ioc.biz.impl.UserBizImpl;
import com.dengrenli.ioc.biz.impl.UserBizImpl2;
/**
* ioc的注入方式及各类类型 有三种注入方式:
*
* set注入
* 基本类型与String
* 数组
* 自定义类型
*
* 构造注入
* 自动装配
* spring4之后出现的
* byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
* byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
*
* @author Administrator
*
*/
public class UserAcion {
private UserBiz userBiz;//自定义类型
private String uname;
private int age;
private List<String> habby;
public UserAcion(String uname, int age) {
super();
this.uname = uname;
this.age = age;
}
public UserAcion() {
super();
}
// public String getUname() {
// return uname;
// }
// public void setUname(String uname) {
// this.uname = uname;
// }
// public int getAge() {
// return age;
// }
// public void setAge(int age) {
// this.age = age;
// }
public List<String> getHabby() {
return habby;
}
public void setHabby(List<String> habby) {
this.habby = habby;
}
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public void upload() {
userBiz.upload();
}
/**
* set 注入问题
*/
public void test1() {
System.out.println(this.uname);
System.out.println(this.age);
System.out.println(this.habby);
}
}
IocTest.java
代码如下:
package com.dengrenli.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dengrenli.ioc.web.OrderAcion;
import com.dengrenli.ioc.web.UserAcion;
public class IocTest {
public static void main(String[] args) {
// UserAcion userAcion=new UserAcion();
// userAcion.upload();
//建模
ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
OrderAcion orderAcion = (OrderAcion) springContext.getBean("ttt");
userAcion.upload();
orderAcion.upload();
userAcion.test1();
}
}
按照我们之前的肯定是在UserAcion里面实现写一个调用继承UserBiz的子类里面内容的方法,然后在测试类IocTest.java里面调用,从而拿到对应子类里面的内容,而我们Spring框架里面要实现这些操作,实现我们先建立属于我们的.xml文件
需要生成我们需要的xml文件,我们需要安装一个插件,安装步骤如下:
如图所示:
点击下载安装就可以了,这样我们就可以建立我们的xml文件了,建立这个插件,主要就是为了生成我们需要的一段代码,代码如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
default-autowire="byType"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
使用步骤如图所示:
勾选上这三个之后点击Finish就可以创建成功了
所以说要不要这个插件也无所谓,因为我们只需要这段代码就行,这段代码在网上都可以找的到
spring-context.xml
id:在容器中查找Bean的id(唯一、且不能以/开头)
class:bean的完整类名
name:在容器中查找Bean的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
scope:(singleton|prototype)默认是singleton
singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
prototype(原型模式/多例模式):一个bean定义对应多个对象实例
abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
parent:指定一个父bean(必须要有继承关系才行)
init-method:指定bean的初始化方法
constructor-arg:使用有参数构造方法创建javaBean
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
default-autowire="byType"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean class="com.dengrenli.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
<bean class="com.dengrenli.ioc.web.UserAcion" id="xxx">
<property name="userBiz" ref="userBiz"></property>
</property>
</bean>
<bean class="com.dengrenli.ioc.web.OrderAcion" id="ttt">
<property name="userBiz" ref="userBiz"></property>
</bean>
</beans>
然后我们来看我们的测试类
IocTest.java
代码如下:
package com.dengrenli.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dengrenli.ioc.web.OrderAcion;
import com.dengrenli.ioc.web.UserAcion;
public class IocTest {
public static void main(String[] args) {
// UserAcion userAcion=new UserAcion();
// userAcion.upload();
//建模
ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
OrderAcion orderAcion = (OrderAcion) springContext.getBean("ttt");
userAcion.upload();
orderAcion.upload();
userAcion.test1();
}
}
每个xxxAcion类里面都定义了一个接口的属性,所以在spring-context.xml文件里面定义它接口实现类bean的class和id,然后在xxxAcion的bean里面的property的ref属性里面等于实现类bean的id,这样调用.upload()方法的时候就会把该接口实现类里面的方法内容拿到。
bean class=com.dengrenli.ioc.web.UserAcionid="xxx"里面的id可以随便等于什么,然后在测试类里面通过springContext.getBean()方法通过它的id拿到相对应的类
OrderAcion.java
代码如下:
package com.dengrenli.ioc.web;
import com.dengrenli.ioc.biz.UserBiz;
import com.dengrenli.ioc.biz.impl.UserBizImpl;
import com.dengrenli.ioc.biz.impl.UserBizImpl2;
public class OrderAcion {
private UserBiz userBiz;
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public void upload() {
userBiz.upload();
}
}
UserAcion.java
代码如下:
package com.dengrenli.ioc.web;
import java.util.List;
import com.dengrenli.ioc.biz.UserBiz;
import com.dengrenli.ioc.biz.impl.UserBizImpl;
import com.dengrenli.ioc.biz.impl.UserBizImpl2;
/**
* ioc的注入方式及各类类型 有三种注入方式:
*
* set注入
* 基本类型与String
* 数组
* 自定义类型
*
* 构造注入
* 自动装配
* spring4之后出现的
* byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
* byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
*
* @author Administrator
*
*/
public class UserAcion {
private UserBiz userBiz;//自定义类型
private String uname;
private int age;
private List<String> habby;
public UserAcion(String uname, int age) {
super();
this.uname = uname;
this.age = age;
}
public UserAcion() {
super();
}
// public String getUname() {
// return uname;
// }
// public void setUname(String uname) {
// this.uname = uname;
// }
// public int getAge() {
// return age;
// }
// public void setAge(int age) {
// this.age = age;
// }
public List<String> getHabby() {
return habby;
}
public void setHabby(List<String> habby) {
this.habby = habby;
}
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public void upload() {
userBiz.upload();
}
/**
* set 注入问题
*/
public void test1() {
System.out.println(this.uname);
System.out.println(this.age);
System.out.println(this.habby);
}
}
明白了我们Spring框架的ioc的基本操作流程后,我们再来了解它的set注入和构造注入以及自动装配
set注入和构造注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
default-autowire="byType"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean class="com.dengrenli.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
<bean class="com.dengrenli.ioc.web.UserAcion" id="xxx">
<!--set注入用property标签 -->
<property name="userBiz" ref="userBiz"></property>
<!-- <property name="uname" value="dengrenli"></property> -->
<!-- <property name="age" value="18"></property> -->
<!-- 构造注入用 <constructor-arg>标签 -->
<constructor-arg name="uname" value="小李"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<property name="habby">
<list>
<value>打篮球</value>
<value>踢足球</value>
<value>敲代码</value>
</list>
</property>
</bean>
<bean class="com.dengrenli.ioc.web.OrderAcion" id="ttt">
<property name="userBiz" ref="userBiz"></property>
</bean>
</beans>
UserAcion.java
代码如下:
package com.dengrenli.ioc.web;
import java.util.List;
import com.dengrenli.ioc.biz.UserBiz;
import com.dengrenli.ioc.biz.impl.UserBizImpl;
import com.dengrenli.ioc.biz.impl.UserBizImpl2;
/**
* ioc的注入方式及各类类型 有三种注入方式:
*
* set注入
* 基本类型与String
* 数组
* 自定义类型
*
* 构造注入
* 自动装配
* spring4之后出现的
* byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
* byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
*
* @author Administrator
*
*/
public class UserAcion {
private UserBiz userBiz;//自定义类型
private String uname;
private int age;
private List<String> habby;
public UserAcion(String uname, int age) {
super();
this.uname = uname;
this.age = age;
}
public UserAcion() {
super();
}
// public String getUname() {
// return uname;
// }
// public void setUname(String uname) {
// this.uname = uname;
// }
// public int getAge() {
// return age;
// }
// public void setAge(int age) {
// this.age = age;
// }
public List<String> getHabby() {
return habby;
}
public void setHabby(List<String> habby) {
this.habby = habby;
}
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public void upload() {
userBiz.upload();
}
/**
* set 注入问题
*/
public void test1() {
System.out.println(this.uname);
System.out.println(this.age);
System.out.println(this.habby);
}
}
结果如图所示:
自动装配
-
自动装配
-
spring4之后出现的
-
byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
如图所示:
设置了它我们就不用来写 property name=“userBiz” ref=“userBiz”></property这句话来指定了,他会自动把上面设置的那个接口实现类给你指定好,所以就不能有两个,有两个的会他会报错,因为它会不知道找那个来自动帮你指定。 -
byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
如图所示:
设置了它我们的接口实现类的bean里面的id就必须要和xxxAction里面定义的接口属性名要保持一致,只有保持一致了才能把这个接口实现类指定给xxxAction
spring的上下文交给tomcat上下文管理
- spring 作为管理整个工程中所有的javabean,
- 那么如何在用户发送请求的时候能够访问到指定的javabean呢?
- 处理方式是:
- 监听器中将spring的上下文交给tomcat的上下文中进行管理
- 思路: 浏览器—>request---->servlertContext---->springContext—>任意的javabean
接下来我们要建一个监听器SpringLoaderListener类,实现ServletContextListener
UserServlet.java
代码如下:
package com.dengrenli.ioc.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* spring 作为管理整个工程中所有的javabean,
* 那么如何在用户发送请求的时候能够访问到指定的javabean呢?
* 处理方式是:
* 监听器中将spring的上下文交给tomcat的上下文中进行管理
* 思路: 浏览器--->request---->servlertContext---->springContext--->任意的javabean
*
* @author Administrator
*
*/
@WebListener
public class SpringLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("tomcat一启动就触发了!!!");
ServletContext tomcatContext= sce.getServletContext(); //拿tomcat的上下文
//拿到在web.xml文件里面给的.xml文件
String springXmlLocation=tomcatContext.getInitParameter("springXmlLocation");
System.out.println("spring的上下文配置文件:"+springXmlLocation);
ApplicationContext springContext=null;
//进行判断如果web.xml文件里面给了.xml文件,就使用在web.xml文件里面给的.xml文件,如果没有那就使用默认的.xml文件
if(springXmlLocation ==null && "".equals(springXmlLocation)) {
//spring的上下文
springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
}else {
springContext=new ClassPathXmlApplicationContext(springXmlLocation);
}
//作用域
tomcatContext.setAttribute("spring_key", springContext);
}
}
web.xml
代码如下:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>springXmlLocation</param-name>
<param-value>/spring-other.xml</param-value>
</context-param>
</web-app>
UserServlet.java
代码如下:
package com.dengrenli.ioc.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
@WebServlet("/user")
public class UserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("处理用户请求");
//通过req.getServletContext()拿到tomcat上下文 然后通过.getAttribute("spring_key");拿到spring的上下文
ApplicationContext springContext=(ApplicationContext) req.getServletContext().getAttribute("spring_key");
UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
userAcion.upload();
}
}
结果如图所示:
谢谢大家,多多指教!!!