Spring Framework学习专题 -- softwbc 发布于:2017年11月15日 浏览量:3015  |

Spring是一个为了解决企业应用开发复杂性而创建的,轻量级的java开发框架。
由Rod Jonhson在Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。

Spring是一个开源一站式的轻量级应用开发框架,抽象了许多应用开发中遇到的共性问题,目的是用于简化开发,能避免重复造轮子,其健壮性、稳定性也在大量的企业应用中得到验证和完善。

它的核心机制是IOC(控制反转)

什么是IoC和DI?DI是如何实现的?

是Inversion of Control的缩写,控制反转是把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理。所谓的”控制反转”就是对组件对象控制权的转移,从程序代码本身转移到了外部容器,由容器来创建对象并管理对象之间的依赖关系。

       DI(Dependency Injection)叫依赖注入,是对IoC更简单的诠释。

依赖注入的基本原则是应用组件不应该负责查找资源或者其他依赖的协作对象。配置对象的工作应该由容器负责,查找资源的逻辑应该从应用组件的代码中抽取出来,交给容器来完成。DI是对IoC更准确的描述,即组件之间的依赖关系由容器在运行期决定,形象的来说,即由容器动态的将某种依赖关系注入到组件之中。

举个例子:

一个类A需要用到接口B中的方法,那么就需要为类A和接口B建立关联或依赖关系,最原始的方法是在类A中创建一个接口B的实现类C的实例,但这种方法需要开发人员自行维护二者的依赖关系,也就是说当依赖关系发生变动的时候需要修改代码并重新构建整个系统。

如果通过一个容器来管理这些对象以及对象的依赖关系,则只需要在类A中定义好用于关联接口B的方法(构造器或setter方法),将类A和接口B的实现类C放入容器中,通过对

容器的配置来实现二者的关联。

依赖注入可以通过setter方法注入(设值注入)、构造器注入和接口注入三种方式来实现,Spring支持setter注入和构造器注入,通常使用构造器注入来注入必须的依赖关系,对于可选的依赖关系,则setter注入是更好的选择,setter注入需要类提供无参构造器或者无参的静态工厂方法来创建对象。


IOC






1.1  AOP

AOPSpring的核心模块之一,与IOC结合使用

AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。OOP引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合。不过OOP允许开发者定义纵向的关系,但并不适合定义横向的关系,例如日志功能。日志代码往往横向地散布在所有对象层次中,而与它对应的对象的核心功能毫无关系对于其他类型的代码,如安全性、异常处理和透明的持续性也都是如此,这种散布在各处的无关的代码被称为横切(cross cutting),在OOP设计中,它导致了大量代码的重复,而不利于各个模块的重用。

AOP技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。

使用"横切"技术,AOP把软件系统分为两个部分:核心关注点横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事物。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。

AOP核心概念

1、横切关注点

对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点

2、切面(aspect

类是对物体特征的抽象,切面就是对横切关注点的抽象

3、连接点(joinpoint

被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器

4、切入点(pointcut

对连接点进行拦截的定义

5、通知(advice

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

6、目标对象

代理的目标对象

7、织入(weave

将切面应用到目标对象并导致代理对象创建的过程

8、引入(introduction

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

SpringAOP的支持

SpringAOP代理由SpringIOC容器负责生成、管理,其依赖关系也由IOC容器负责管理。因此,AOP代理可以直接使用容器中的其它bean实例作为目标,这种关系可由IOC容器的依赖注入提供。Spring创建代理的规则为:

1默认使用Java动态代理来创建AOP代理,这样就可以为任何接口实例创建代理了

2当需要代理的类不是代理接口的时候,Spring会切换为使用CGLIB代理,也可强制使用CGLIB

AOP编程其实是很简单的事情,纵观AOP编程,程序员只需要参与三个部分:

1、定义普通业务组件

2、定义切入点,一个切入点可能横切多个业务组件

3、定义增强处理,增强处理就是在AOP框架为普通业务组件织入的处理动作

所以进行AOP编程的关键就是定义切入点和定义增强处理,一旦定义了合适的切入点和增强处理,AOP框架将自动生成AOP代理,即:代理对象的方法=增强处理+被代理对象的方法。

下面给出一个Spring AOP.xml文件模板,名字叫做aop.xml,之后的内容都在aop.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: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-4.2.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

           

</beans>

复制代码

基于SpringAOP简单实现

注意一下,在讲解之前,说明一点:使用Spring AOP,要成功运行起代码,只用Spring提供给开发者的jar包是不够的,请额外上网下载两个jar包:

1aopalliance.jar

2aspectjweaver.jar

开始讲解用Spring AOPXML实现方式,先定义一个接口:

public interface HelloWorld

{

    void printHelloWorld();

    void doPrint();

}

定义两个接口实现类:

复制代码

public class HelloWorldImpl1 implements HelloWorld

{

    public void printHelloWorld()

    {

        System.out.println("Enter HelloWorldImpl1.printHelloWorld()");

    }

   

    public void doPrint()

    {

        System.out.println("Enter HelloWorldImpl1.doPrint()");

        return ;

    }

}

复制代码

复制代码

public class HelloWorldImpl2 implements HelloWorld

{

    public void printHelloWorld()

    {

        System.out.println("Enter HelloWorldImpl2.printHelloWorld()");

    }

   

    public void doPrint()

    {

        System.out.println("Enter HelloWorldImpl2.doPrint()");

        return ;

    }

}

复制代码

横切关注点,这里是打印时间:

复制代码

public class TimeHandler

{

    public void printTime()

    {

        System.out.println("CurrentTime = " + System.currentTimeMillis());

    }

}

复制代码

有这三个类就可以实现一个简单的Spring AOP了,看一下aop.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: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-4.2.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

       

        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />

        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />

        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />

       

        <aop:config>

            <aop:aspect id="time" ref="timeHandler">

                <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />

                <aop:before method="printTime" pointcut-ref="addAllMethod" />

                <aop:after method="printTime" pointcut-ref="addAllMethod" />

            </aop:aspect>

        </aop:config>

</beans>

复制代码

写一个main函数调用一下:

复制代码

public static void main(String[] args)

{

    ApplicationContext ctx =

            new ClassPathXmlApplicationContext("aop.xml");

       

    HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1");

    HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2");

    hw1.printHelloWorld();

    System.out.println();

    hw1.doPrint();

   

    System.out.println();

    hw2.printHelloWorld();

    System.out.println();

    hw2.doPrint();

}

复制代码

运行结果为:

复制代码

CurrentTime = 1446129611993

Enter HelloWorldImpl1.printHelloWorld()

CurrentTime = 1446129611993

 

CurrentTime = 1446129611994

Enter HelloWorldImpl1.doPrint()

CurrentTime = 1446129611994

 

CurrentTime = 1446129611994

Enter HelloWorldImpl2.printHelloWorld()

CurrentTime = 1446129611994

 

CurrentTime = 1446129611994

Enter HelloWorldImpl2.doPrint()

CurrentTime = 1446129611994

复制代码

看到给HelloWorld接口的两个实现类的所有方法都加上了代理,代理内容就是打印时间

基于SpringAOP使用其他细节

1、增加一个横切关注点,打印日志,Java类为:

复制代码

public class LogHandler

{

    public void LogBefore()

    {

        System.out.println("Log before method");

    }

   

    public void LogAfter()

    {

        System.out.println("Log after method");

    }

}

复制代码

复制代码

<?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: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-4.2.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

       

        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />

        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />

        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />

        <bean id="logHandler" class="com.xrq.aop.LogHandler" />

       

        <aop:config>

            <aop:aspect id="time" ref="timeHandler" order="1">

                <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />

                <aop:before method="printTime" pointcut-ref="addTime" />

                <aop:after method="printTime" pointcut-ref="addTime" />

            </aop:aspect>

            <aop:aspect id="log" ref="logHandler" order="2">

                <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />

                <aop:before method="LogBefore" pointcut-ref="printLog" />

                <aop:after method="LogAfter" pointcut-ref="printLog" />

            </aop:aspect>

        </aop:config>

</beans>

复制代码

测试类不变,打印结果为:

复制代码

CurrentTime = 1446130273734

Log before method

Enter HelloWorldImpl1.printHelloWorld()

Log after method

CurrentTime = 1446130273735

 

CurrentTime = 1446130273736

Log before method

Enter HelloWorldImpl1.doPrint()

Log after method

CurrentTime = 1446130273736

 

CurrentTime = 1446130273736

Log before method

Enter HelloWorldImpl2.printHelloWorld()

Log after method

CurrentTime = 1446130273736

 

CurrentTime = 1446130273737

Log before method

Enter HelloWorldImpl2.doPrint()

Log after method

CurrentTime = 1446130273737

复制代码

要想让logHandlertimeHandler前使用有两个办法:

1aspect里面有一个order属性,order属性的数字就是横切关注点的顺序

2)把logHandler定义在timeHandler前面,Spring默认以aspect的定义顺序作为织入顺序

2、我只想织入接口中的某些方法

修改一下pointcutexpression就好了:

复制代码

<?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: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-4.2.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

       

        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />

        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />

        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />

        <bean id="logHandler" class="com.xrq.aop.LogHandler" />

       

        <aop:config>

            <aop:aspect id="time" ref="timeHandler" order="1">

                <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.print*(..))" />

                <aop:before method="printTime" pointcut-ref="addTime" />

                <aop:after method="printTime" pointcut-ref="addTime" />

            </aop:aspect>

            <aop:aspect id="log" ref="logHandler" order="2">

                <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.do*(..))" />

                <aop:before method="LogBefore" pointcut-ref="printLog" />

                <aop:after method="LogAfter" pointcut-ref="printLog" />

            </aop:aspect>

        </aop:config>

</beans>

复制代码

表示timeHandler只会织入HelloWorld接口print开头的方法,logHandler只会织入HelloWorld接口do开头的方法

3、强制使用CGLIB生成代理

前面说过Spring使用动态代理或是CGLIB生成代理是有规则的,高版本的Spring会自动选择是使用动态代理还是CGLIB生成代理内容,当然我们也可以强制使用CGLIB生成代理,那就是<aop:config>里面有一个"proxy-target-class"属性,这个属性值如果被设置为true,那么基于类的代理将起作用,如果proxy-target-class被设置为false或者这个属性被省略,那么基于接口的代理将起作用







Spring AOP拦截器调用实现


对象行为增强

它是一个生成通知器链的工厂。

拦截器存在List中,list中的拦截器会被JDK生成的AopProxy代理对象的invoke方法或者CGLIB代理对象的intercept拦截方法取得,调用。





1.1  SpringMVC运行原理

Spring MVC主要由DispatcherServlet、处理器映射、处理器(控制器)、视图解析器、视图组成。他的两个核心是两个核心:

处理器映射:选择使用哪个控制器来处理请求
视图解析器:选择结果应该如何渲染

通过以上两点,Spring MVC保证了如何选择控制处理请求和如何选择视图展现输出之间的松耦合。

(1)http请求:客户端请求提交到DispatcherServlet。 
(2)寻找处理器:由DispatcherServlet控制器查询一个或多个HandlerMapping,找到处理请求的Controller。 
(3) 调用处理器:DispatcherServlet将请求提交到Controller。
(4)(5)调用业务处理和返回结果:Controller调用业务逻辑处理后,返回ModelAndView。
(6)(7)处理视图映射并返回模型:DispatcherServlet查询一个或多个ViewResoler视图解析器,找到ModelAndView指定的视图。
(8)http响应:视图负责将结果显示到客户端。

接口解释

(1)DispatcherServlet接口
Spring提供的前端控制器,所有的请求都有经过它来统一分发。在DispatcherServlet将请求分发给Spring Controller之前,需要借助于Spring提供的HandlerMapping定位到具体的Controller。
(2)HandlerMapping接口
能够完成客户请求到Controller映射。
(3)Controller接口
需要为并发用户处理上述请求,因此实现Controller接口时,必须保证线程安全并且可重用。
Controller将处理用户请求,这和Struts Action扮演的角色是一致的。一旦Controller处理完用户请求,则返回ModelAndView对象给DispatcherServlet前端控制器,ModelAndView中包含了模型(Model)和视图(View)。 
从宏观角度考虑,DispatcherServlet是整个Web应用的控制器;从微观考虑,Controller是单个Http请求处理过程中的控制器,而ModelAndView是Http请求过程中返回的模型(Model)和视图(View)。
4ViewResolver接口
Spring提供的视图解析器(ViewResolver)在Web应用中查找View对象,从而将相应结果渲染给客户。

DispatcherServlet是整个Spring MVC的核心。它负责接收HTTP请求组织协调Spring MVC的各个组成部分。其主要工作有以下三项:
(1)截获符合特定格式的URL请求。
(2)初始化DispatcherServlet上下文对应WebApplicationContext,并将其与业务层、持久化层的WebApplicationContext建立关联。
(3)初始化Spring MVC的各个组成组件,并装配到DispatcherServlet中。




Tomcat为例

这个DispatcherServletMVC中很重要的一个类,起着分发请求的作用。


1.1  SpringMVC参数绑定

1、处理request uri部分(URI template中Variable,不含queryString部分)的注解@PathVariable

2、处理request header部分的注解:@RequestHeader @CookieValue

3、request body部分的注解:@RequestParam @RequestBody

4、处理attribute类型的注解:@SessionAttribute @ModelAttribute

 

1.2  @Autowired@Resource的区别

@Resource@Autowired都是做bean的注入时使用,其实@Resource并不是Spring的注解,它的包是javax.annotation.Resource,需要导入,但是Spring支持该注解的注入。

1、共同点

两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法。

2、不同点

1@Autowired

@AutowiredSpring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。

复制代码

public class TestServiceImpl {

    // 下面两种@Autowired只要使用一种即可

    @Autowired

    private UserDao userDao; // 用于字段上

   

    @Autowired

    public void setUserDao(UserDao userDao) { // 用于属性的方法上

        this.userDao = userDao;

    }

}

复制代码

@Autowired注解是按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。如下:

public class TestServiceImpl {

    @Autowired

    @Qualifier("userDao")

    private UserDao userDao;

}

2@Resource

@Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource@Resource有两个重要的属性:nametype,而Spring@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。

复制代码

public class TestServiceImpl {

    // 下面两种@Resource只要使用一种即可

    @Resource(name="userDao")

    private UserDao userDao; // 用于字段上

   

    @Resource(name="userDao")

    public void setUserDao(UserDao userDao) { // 用于属性的setter方法上

        this.userDao = userDao;

    }

}

复制代码

注:最好是将@Resource放在setter方法上,因为这样更符合面向对象的思想,通过setget去操作属性,而不是直接去操作属性。

@Resource装配顺序:

如果同时指定了nametype,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。

如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。

如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

@Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

 

1.3  SpringMVC数据转换、格式化、校验

 

1.4  SpringMVC参数解析器

1.4.1       HandlerMethodArgumentResolver

HandlerMethodArgumentResolver是用来为处理器解析参数的,主要用在HandlerMethod中,每个Resolver对应一种类型的参数,其实现类特别的多。

HandlerMethodArgumentResolver的接口定义如下:

(1)supportsParameter 用于判断是否支持对某种参数的解析

(2)resolveArgument  将请求中的参数值解析为某种对象

/**
 * Strategy interface for resolving method parameters into argument values in
 * the context of a given request.
 *
 * @author Arjen Poutsma
 * @since 3.1
 */
public interface HandlerMethodArgumentResolver {

/**
    * Whether the given {@linkplain MethodParameter method parameter} is
    * supported by this resolver.
    * @param
parameter the method parameter to check
    * @return {@code true} if this resolver supports the supplied parameter;
    * {@code false} otherwise
    */
boolean supportsParameter(MethodParameter parameter);

/**
    * Resolves a method parameter into an argument value from a given request.
    * A {@link ModelAndViewContainer} provides access to the model for the
    * request. A {@link WebDataBinderFactory} provides a way to create
    * a {@link WebDataBinder} instance when needed for data binding and
    * type conversion purposes.
    * @param
parameter the method parameter to resolve. This parameter must
    * have previously been passed to
    * {@link #supportsParameter(org.springframework.core.MethodParameter)}
    * and it must have returned {@code true}
    * @param
mavContainer the ModelAndViewContainer for the current request
    * @param
webRequest the current request
    * @param
binderFactory a factory for creating {@link WebDataBinder} instances
    * @return the resolved argument value, or {@code null}.
    * @throws Exception in case of errors with the preparation of argument values
    */
Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception;

}


HandlerMethodArgumentResolver的执行流程:

参数的处理是在InvocableHandlerMethod中,当执行具体的请求处理时执行invokeForRequest函数

/**
 * Invoke the method after resolving its argument values in the context of the given request.
 *
<p>Argument values are commonly resolved through {@link HandlerMethodArgumentResolver}s.
 * The {@code provideArgs} parameter however may supply argument values to be used directly,
 * i.e. without argument resolution. Examples of provided argument values include a
 * {@link WebDataBinder}, a {@link SessionStatus}, or a thrown exception instance.
 * Provided argument values are checked before argument resolvers.
 * @param
request the current request
 * @param
mavContainer the ModelAndViewContainer for this request
 * @param
providedArgs "given" arguments matched by type, not resolved
 * @return the raw value returned by the invoked method
 * @exception Exception raised if no suitable argument resolver can be found,
 * or if the method raised an exception
 */
public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
   Object[] args = getMethodArgumentValues(request
, mavContainer, providedArgs);
……
}


具体的参数解析器的选择和使用参数解析器去解析参数的实现都在getMethodArgumentValues中,首先springMVC在启动时会将所有的参数解析器放到HandlerMethodArgumentResolverComposite,HandlerMethodArgumentResolverComposite是所有参数的一个集合,接下来就是从HandlerMethodArgumentResolverComposite参数解析器集合中选择一个支持对parameter解析的参数解析器,接下来就使用支持参数解析的解析器进行参数解析。

/**
 * Get the method argument values for the current request.
 */
private Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
   MethodParameter[] parameters = getMethodParameters()
;
Object[] args = new Object[parameters.length];
   for
(int i = 0; i < parameters.length; i++) {
      MethodParameter parameter = parameters[i]
;
parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
args[i] = resolveProvidedArgument(parameter, providedArgs);
      if
(args[i] != null) {
continue;
}
if (this.argumentResolvers.supportsParameter(parameter)) {
try {
            args[i] =
this.argumentResolvers.resolveArgument(
                  parameter
, mavContainer, request, this.dataBinderFactory);
            continue;
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
}
throw ex;
}
      }
if (args[i] == null) {
         String msg = getArgumentResolutionErrorMessage(
"No suitable resolver for argument", i);
         throw new
IllegalStateException(msg);
}
   }
return args;
}


以上代码会将我们通过链接提交的参数值转换为对象值。

1.4.2       HandlerMethodArgumentResolverComposite

HandlerMethodArgumentResolverComposite,其简单来说就是所有的参数解析器的链表,保存了springMVC提供的所有的参数解析器,采用职责链的模式来完成参数解析器的查找,并完成参数解析生成目标对象。完整源码及说明如下:

/**
 * Resolves method parameters by delegating to a list of registered {@link HandlerMethodArgumentResolver}s.
 * Previously resolved method parameters are cached for faster lookups.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgumentResolver {
protected final Log logger = LogFactory.getLog(getClass());
//保存springMVC提供的所有的参数解析器
   private final
List<HandlerMethodArgumentResolver>argumentResolvers =
new LinkedList<HandlerMethodArgumentResolver>();
//用于缓存已经查找过的参数解析器
   private final
Map<MethodParameter, HandlerMethodArgumentResolver>argumentResolverCache =
new ConcurrentHashMap<MethodParameter, HandlerMethodArgumentResolver>(256);
/**获取所有的参数解析器
    * Return a read-only list with the contained resolvers, or an empty list.
    */
public List<HandlerMethodArgumentResolver>getResolvers() {
return Collections.unmodifiableList(this.argumentResolvers);
}
/** 判断参数解析器是否支持参数解析
    * Whether the given {@linkplain MethodParameter method parameter} is supported by any registered
    * {@link HandlerMethodArgumentResolver}.
    */
@Override
public boolean supportsParameter(MethodParameter parameter) {
return getArgumentResolver(parameter) != null;
}
/**返回参数解析器解析后的数据
    * Iterate over registered {@link HandlerMethodArgumentResolver}s and invoke the one that supports it.
    * @throws IllegalStateException if no suitable {@link HandlerMethodArgumentResolver} is found.
    */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
      HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter)
;
Assert.notNull(resolver, "Unknown parameter type [" + parameter.getParameterType().getName() + "]");
      return
resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}
/** 获取支持某个参数解析的参数解析器
    * Find a registered {@link HandlerMethodArgumentResolver} that supports the given method parameter.
    */
private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
      HandlerMethodArgumentResolver result =
this.argumentResolverCache.get(parameter);
      if
(result == null) {
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
if (logger.isTraceEnabled()) {
logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" +
                     parameter.getGenericParameterType() +
"]");
}
if (methodArgumentResolver.supportsParameter(parameter)) {
               result = methodArgumentResolver
;
               this
.argumentResolverCache.put(parameter, result);
               break;
}
         }
      }
return result;
}
/**添加参数解析器
    * Add the given {@link HandlerMethodArgumentResolver}.
    */
public HandlerMethodArgumentResolverComposite addResolver(HandlerMethodArgumentResolver resolver) {
this.argumentResolvers.add(resolver);
      return this;
}
/**获取参数解析器集合
    * Add the given {@link HandlerMethodArgumentResolver}s.
    */
public HandlerMethodArgumentResolverComposite addResolvers(List<? extends HandlerMethodArgumentResolver> resolvers) {
if (resolvers != null) {
for (HandlerMethodArgumentResolver resolver : resolvers) {
this.argumentResolvers.add(resolver);
}
      }
return this;
}
}


1.4.3       RequestParamMethodArgumentResolver(其一实现类)

是HandlerMethodArgumentResolver的一个具体实现类。通过它来简单介绍一下具体的参数解析过程。RequestParamMethodArgumentResolver简单来说就是对一个请求参数值的解析,将请求中的参数值解析成为Controller函数中参数需要的具体数据类型。

Controller中函数需要的参数

1.   @RequestMapping("/getdata")  

2.   @ResponseBody  

3.   public Object getData(String name,Integer age){  

4.       return name+""+age;  

5.  }  

我们发起的请求链接

http://localhost/product/getdata.action?name=admin&age=10

接下来我们跟踪一下代码看看springMVC是如何将请求中的参数name=admin和age=10解析成为函数中需要的具体数据类型String和Integer。

首先参数解析会到AbstractNamedValueMethodArgumentResolver类的resolveArgument函数,如下图



首先会获取request中的参数name及值,接下来是在RequestParamMethodArgumentResolver类的resolveName函数中获取这个参数的值

1.   protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {  

2.       ......    

3.       if (arg == null) {  

4.           String[] paramValues = webRequest.getParameterValues(name);  

5.           if (paramValues != null) {  

6.               arg = (paramValues.length == 1 ? paramValues[0] : paramValues);  

7.           }  

8.       }  

9.       return arg;  

10.  }  

上面代码的执行如下图:

这样就获取了name=admini这个值。

参数转换的过程主要是在AbstractNamedValueMethodArgumentResolver类的resolveArgument函数中,主要是获取参数值和将参数转换为Controller中函数需要的参数类型。

1.   @Override  

2.   public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {  

3.      Class<?> paramType = parameter.getParameterType();  

4.       NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);  

5.      //request中获取参数值  

6.       Object arg = resolveName(namedValueInfo.name, parameter, webRequest);  

7.       if (arg == null) {  

8.           if (namedValueInfo.defaultValue != null) {  

9.               arg = resolveDefaultValue(namedValueInfo.defaultValue);  

10.          }  else if (namedValueInfo.required && !parameter.getParameterType().getName().equals("java.util.Optional")) {  

11.              handleMissingValue(namedValueInfo.name, parameter);  

12.          }  

13.          arg = handleNullValue(namedValueInfo.name, arg, paramType);  

14.      }  else if ("".equals(arg) && namedValueInfo.defaultValue != null) {  

15.          arg = resolveDefaultValue(namedValueInfo.defaultValue);  

16.      }  

17.      //将获取的参数值转换为Controller中函数需要的数据类型  

18.      if (binderFactory != null) {  

19.          WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name); 

20.          try {  

21.              arg = binder.convertIfNecessary(arg, paramType, parameter);  

22.          }catch (ConversionNotSupportedException ex) {  

23.              throw new MethodArgumentConversionNotSupportedException(arg, ex.getRequiredType(),  

24.                          namedValueInfo.name, parameter, ex.getCause());  

25.          } catch (TypeMismatchException ex) {  

26.              throw new MethodArgumentTypeMismatchException(arg, ex.getRequiredType(),  

27.                          namedValueInfo.name, parameter, ex.getCause());  

28.          }  

29.      }  

30.      handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);  

31.      return arg;  

32.  }  

http://blog.csdn.net/qq924862077/article/details/54177442

1.1  SpringMVC拦截器

<mvc:interceptors>
<bean
id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property
name="paramName" value="lang" />
</bean>
<
mvc:interceptor>
<
mvc:mapping path="/**"/>
<
mvc:exclude-mapping path="/"/>
<bean
class="com.xinhuanet.apply.interceptor.LogInterceptor"/>
</
mvc:interceptor>
</
mvc:interceptors>


处理器拦截器,用于对处理器进行预处理和后处理。

应用场景:日志记录,权限检查,性能监控,通用行为

符合横切关注点的所有功能都可以放入拦截器实现

public interface HandlerInterceptor {}

public abstract class HandlerInterceptorAdapter implements HandlerInterceptor

内部在DispatcherServletdoDispatch对配置的拦截器调用。

1.2  <mvc:annotation-driven/>和<context:annotation-config/>

  Spring家族的配置中这两个配置的意义,说具体点其实根据标签的shecma就能看出来,mvc,主要就是为了Spring MVC来用的,提供Controller请求转发,json自动转换等功能,而context这个主要是解决spring容器的一些注解。

  从百度参考了两个帖子:

    http://blog.csdn.net/sxbjffsg163/article/details/9955511

    http://blog.sina.com.cn/s/blog_872758480100wtfh.html

<mvc:annotation-driven />是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学都快速应用默认配置方案。<mvc:annotation-driven />会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。

并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
后面,我们处理响应ajax请求时,就使用到了对json的支持。
后面,对action写JUnit单元测试时,要从spring IOC容器中取DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,来完成测试,取的时候要知道是<mvc:annotation-driven />这一句注册的这两个bean。

 

<context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> is actually rather pointless. It declares explicit support for annotation-driven MVC controllers (i.e.@RequestMapping, @Controller, etc), even though support for those is the default behaviour.

My advice is to always declare <context:annotation-config>, but don't bother with <mvc:annotation-driven /> unless you want JSON support via Jackson.

 

在基于主机方式配置Spring的配置文件中,你可能会见到<context:annotation-config/>这样一条配置,他的作用是式地向Spring容器注册

AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、

PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。

注册这4个 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。

例如:

如果你想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。传统声明方式如下

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor

如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。

如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。同样,传统的声明方式如下:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>的简化配置方式,自动帮你完成声明。

   不过,呵呵,我们使用注解一般都会配置扫描包路径选项

<context:component-scan base-package=”XX.XX”/>

    该配置项其实也包含了自动注入上述processor的功能,因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。

1.3      Spring事件监听(发布和接收定制事件、事件传播)

事件传播

ApplicationContext基于Observer模式(java.util包中有对应实现),提供了针对Bean的事件传播功能。通过Application. publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener。

事件传播的一个典型应用是,当Bean中的操作发生异常(如数据库连接失败),则通过事件传播机制通知异常监听器进行处理。在笔者的一个项目中,就曾经借助事件机制,较好的实现了当系统异常时在监视终端上报警,同时发送报警SMS至管理员手机的功能。

 

ApplicationContext容器提供了容器内部事件发布功能,是继承自JavaSE标准自定义事件类而实现的。

 

JavaSE标准自定义事件结构不在此详细描述,一张图很直观的描述清楚:



EventObject,为JavaSE提供的事件类型基类,任何自定义的事件都继承自该类,例如上图中右侧灰色的各个事件。spring中提供了该接口的子类ApplicationEvent。

 

EventListener为JavaSE提供的事件监听者接口,任何自定义的事件监听者都实现了该接口,如上图左侧的各个事件监听者。Spring中提供了该接口的子类ApplicationListener接口。

 

JavaSE中未提供事件发布者这一角色类,由各个应用程序自行实现事件发布者这一角色。Spring中提供了ApplicationEventPublisher接口作为事件发布者,并且ApplicationContext实现了这个接口,担当起了事件发布者这一角色。但ApplicationContext在具体实现上有所差异,Spring提供了ApplicationEventMulticaster接口,负责管理ApplicationListener和发布ApplicationEvent。ApplicationContext会把相应的事件相关工作委派给ApplicationEventMulticaster接口实现类来做。类图如下所示:

 

 

 

事件发布时序图如下:

 

-------------------------------------------------------------------------------------------------

Spring中提供一些Aware相关的接口,BeanFactoryAware ApplicationContextAwareResourceLoaderAwareServletContextAware等等,其中最常用到的是ApplicationContextAware。实现ApplicationContextAwareBean,在Bean被初始后,将会被注入ApplicationContext的实例。ApplicationContextAware提供了publishEvent()方法,实现Observer(观察者)设计模式的事件传播机,提供了针对Bean的事件传播功能。通过Application.publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener

 

Spring事件处理一般过程:

 

◆定义Event类,继承org.springframework.context.ApplicationEvent

◆编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口。

◆覆盖方法setApplicationContext(ApplicationContext applicationContext)和发布方法publish(Object obj)

◆定义时间监听类EventListener,实现ApplicationListener接口,实现方法onApplicationEvent(ApplicationEvent event)

 

1.发布

    1.1事件的发布者需要实现的接口

        org.springframework.context.ApplicationEventPublisherAware

    1.2 代码示例

import org.springframework.context.ApplicationEventPublisher;

import org.springframework.context.ApplicationEventPublisherAware;

 

/**

 *

 * @author zq

 *

 */

public class HelloWorld implements ApplicationEventPublisherAware{

 private String word;

 private ApplicationEventPublisher tradeEventPublisher;

 

 public void setWord(String w){

  this.word = w;

 }

 

 public void say(){

  System.out.println("say : "+ this.word);

  //construct a TradeEvent instance and publish it

  TradeEvent tradeEvent = new TradeEvent(new String("tradeEvent"));

  this.tradeEventPublisher.publishEvent(tradeEvent);

 }

 

 @Override

 public void setApplicationEventPublisher(

   ApplicationEventPublisher applicationEventPublisher) {

  // TODO Auto-generated method stub

  this.tradeEventPublisher = applicationEventPublisher;

 }

}

 

2.接受事件

  2.1需要实现的接口org.springframework.context.ApplicationListener

  2.2代码示例

import org.springframework.context.ApplicationEvent;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextStartedEvent;

 

public class TradeContextListener implements ApplicationListener{

 

 @Override

 public void onApplicationEvent(ApplicationEvent e) {

 

  System.out.println(e.getClass().toString());

  // TODO Auto-generated method stub

  if (e instanceof ContextStartedEvent){

   System.out.println("it was contextStartedEvent");

  }

 

  if (e instanceof TradeEvent){

   System.out.println(e.getSource());

  }

 

 }

 

}

 

3配置文件

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean name="helloWorld" class="study.HelloWorld">

<property name="word" value="hello world"/>

</bean>

 

<bean id="tradeContextListener" class="study.TradeContextListener"/>

</beans>

 

4.测试代码

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

import study.HelloWorld;

public class TestHelloWorld {

 

 /**

  * @param args

  */

 public static void main(String[] args) {

  // TODO Auto-generated method stub

 

  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("study-context.xml");

  HelloWorld bean = (HelloWorld)applicationContext.getBean("helloWorld");

  bean.say();

 }

 

}

 

 

SpringApplicationContext的事件机制--- 内定事件)

Spring中已经定义了五个标准事件,分别介绍如下:

1)      ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。

 

2)      ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。

 

3)      RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。

 

ContestStartedEventSpring2.5新增的事件,当容器调用ConfigurableApplicationContextStart()方法开始/重新开始容器时触发该事件。

 

5) ContestStopedEventSpring2.5新增的事件,当容器调用ConfigurableApplicationContextStop()方法停止容器时触发该事件。

 

下面通过一个例子展示如何处理Spring内定的事件(例程3.8)。创建一个Java工程,添加Spring开发能力后,新建ioc.test包。在包中新建ApplicationEventListener类,实现ApplicationListener接口,在onApplicationEvent()方法中添加事件处理代码,如下:

 

1 package ioc.test;

2

3 //Import省略

4 publicclass ApplicationEventListenerimplements ApplicationListener {

5

6 publicvoid onApplicationEvent(ApplicationEvent event) {

7

8 //如果是容器刷新事件

9 if(eventinstanceof ContextClosedEvent ){

10             System.out.println(event.getClass().getSimpleName()+" 事件已发生!");  

11         }elseif(eventinstanceof ContextRefreshedEvent ){//如果是容器关闭事件

12             System.out.println(event.getClass().getSimpleName()+" 事件已发生!");  

13         }elseif(eventinstanceof ContextStartedEvent ){

14             System.out.println(event.getClass().getSimpleName()+" 事件已发生!");

15         }elseif(eventinstanceof ContextStoppedEvent){

16             System.out.println(event.getClass().getSimpleName()+" 事件已发生!");

17         }else{

18             System.out.println("有其它事件发生:"+event.getClass().getName());

19         }

20                   

21     }

22

23 }

24

Spring配置文件中定义一个Bean,类为ApplicationEventListener,代码如下:

 

1 <?xml version="1.0" encoding="UTF-8"?>

2 <beans…………  

3

4    <bean id="ApplicationEventListener" class="ioc.test.ApplicationEventListener"/>

5

6 </beans>

7

添加含有主方法的TesMain类,在主方法中,调用容器的相应方法,触发Spring内定事件,代码如下:

 

1 package ioc.test;

2

3 //import省略

4 publicclass TesMain {

5

6 publicstaticvoid main(String[] args) {

7         AbstractApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");

8        

9

10 //    ac.refresh();//触发ContextRefreshedEvent事件

11         ac.start();//触发ContextStartedEvent事件

12         ac.stop(); //触发ContextStoppedEvent事件

13         ac.close();//关闭容器,触发ContextClosedEvent事件

14

15     }

16 }

17

运行主类,控制台输出如下:



从例子中可以知道,要注册事件监听器,我们只需要把它配置成一个Bean即可,ApplicationContext容器会自动将其注册。

 

1.1      数据校验 JSR303

JSR-303  JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是  Hibernate Validator。此实现与 Hibernate ORM 没有任何关系。 JSR 303 用于对 Java Bean 中的字段的值进行验证。Spring MVC 3.x 之中也大力支持 JSR-303,可以在控制器中对表单提交的数据方便地验证。

 

JSR 303 内置的约束规则:

@AssertTrue / @AssertFalse 

验证适用字段: boolean  

注解说明:验证值是否为 true / false 

属性说明: - 

@DecimalMax / @DecimalMin   验证适用字段: BigDecimal,BigInteger,String,byte,short,int,long  注解说明:验证值是否小于或者等于指定的小数值,要注意小数存在精度问题 属性说明:公共

@Digits   验证适用字段: BigDecimal,BigInteger,String,byte,short,int,long  注解说明:验证值的数字构成是否合法 属性说明: integer:指定整数部分的数字的位数。 fraction: 指定小数部分的数字的位数。

@Future / @Past   验证适用字段: Date,Calendar   注解说明:验证值是否在当前时间之后 / 之前 属性说明:公共

 

@Max / @Min   验证适用字段: BigDecimal,BigInteger,String,byte,short,int,long  注解说明:验证值是否小于或者等于指定的整数值 属性说明:公共 @NotNull / @Null   验证适用字段:引用数据类型 注解说明:验证值是否为非空 /  属性说明:公共 @Pattern   验证适用字段: String   注解说明:验证值是否配备正则表达式 属性说明: regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。 @Size   验证适用字段: String,Collection,Map,数组 注解说明:验证值是否满足长度要求 属性说明: max:指定最大长度, min:指定最小长度。

 

@Valid   验证适用字段:引用类型 注解说明:验证值是否需要递归验证 属性说明:无

 

https://yq.aliyun.com/articles/28725

 

JSR-303  JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是Hibernate Validator

此实现与 Hibernate ORM 没有任何关系。 JSR 303 用于对 Java Bean 中的字段的值进行验证。 
Spring MVC 3.x 
之中也大力支持 JSR-303,可以在控制器中对表单提交的数据方便地验证。 
:可以使用注解的方式进行验证

准备校验时使用的JAR

validation-api-1.0.0.GA.jarJDK的接口; 
hibernate-validator-4.2.0.Final.jar
是对上述接口的实现; 
log4j
slf4jslf4j-log4j

JSR 303 基本的校验规则

空检查 
@Null 
验证对象是否为null 
@NotNull 
验证对象是否不为null, 无法查检长度为0的字符串 
@NotBlank 
检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格
@NotEmpty 
检查约束元素是否为NULL或者是EMPTY.

Booelan检查 
@AssertTrue 
验证 Boolean 对象是否为 true 
@AssertFalse 
验证 Boolean 对象是否为 false

长度检查 
@Size(min=, max=) 
验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 
@Length(min=, max=) Validates that the annotated string is between min and max included.

日期检查 
@Past 
验证 Date  Calendar 对象是否在当前时间之前,验证成立的话被注释的元素一定是一个过去的日期 
@Future 
验证 Date  Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期 
@Pattern 
验证 String 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。

数值检查 
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng”“,Integernull 
@Min 
验证 Number  String 对象是否大等于指定的值 
@Max 
验证 Number  String 对象是否小等于指定的值 
@DecimalMax 
被标注的值必须不大于约束中指定的最大值这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度 
@DecimalMin 
被标注的值必须不小于约束中指定的最小值这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度 
@Digits 
验证 Number  String 的构成是否合法 
@Digits(integer=,fraction=) 
验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。 
@Range(min=, max=) 
被指定的元素必须在合适的范围内 
@Range(min=10000,max=50000,message=”range.bean.wage”) 
@Valid 
递归的对关联对象进行校验如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证
@CreditCardNumber
信用卡验证 
@Email 
验证是否是邮件地址,如果为null,不进行验证,算通过验证。 
@ScriptAssert(lang= ,script=, alias=) 
@URL(protocol=,host=, port=,regexp=, flags=)

案例分析

在使用的时候直接对JavaBean进行注解既可以实现对属性的验证

public class Order {
    // 必须不为 null, 大小是 10
    @NotNull
    @Size(min = 10, max = 10)
    private String orderId;
    // 必须不为空
    @NotEmpty
    private String customer;
    // 必须是一个电子信箱地址
    @Email
    private String email;
    // 必须不为空
    @NotEmpty
    private String address;
    // 必须不为 null, 必须是下面四个字符串'created', 'paid', 'shipped', 'closed'其中之一
    // @Status 是一个定制化的 contraint
    @NotNull
    @Status
    private String status;
    // 必须不为 null
    @NotNull
    private Date createDate;
    // 嵌套验证
    @Valid
    private Product product;
 
   // getter 和setter方法
}
 


又例:

    @NotNull(message = "adultTax不能为空")
    private Integer adultTax;
 
    @NotNull(message = "adultTaxType不能为空")
    @Min(value = 0, message = "adultTaxType 的最小值为0")
    @Max(value = 1, message = "adultTaxType 的最大值为1")
    private Integer adultTaxType;
 
    @NotNull(message = "reason信息不可以为空")
    @Pattern(regexp = "[1-7]{1}", message = "reason的类型值为1-7中的一个类型")
private String reason;//订单取消原因
下边是一个完整的例子:
public class ValidateTestClass{
    @NotNull(message = "reason信息不可以为空")
    @Pattern(regexp = "[1-7]{1}", message = "reason的类型值为1-7中的一个类型")
    private String reason;//订单取消原因
    //get、set方法、有参构造方法、无参构造方法、toString方法省略
    /**
     * 验证参数:就是验证上述注解的完整方法
     * @return
     */
    public void validateParams() {
        //调用JSR303验证工具,校验参数
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<ValidateTestClass>> violations = validator.validate(this);
        Iterator<ConstraintViolation<ValidateTestClass>> iter = violations.iterator();
        if (iter.hasNext()) {
            String errMessage = iter.next().getMessage();
            throw new ValidationException(errMessage);
        }
    }
}


我们可以写一个测试类进行验证:

public class ValidateTestClassValidateTest{
 
    @Test
    public void validateParam(){
        ValidateTestClass validateTestClass = new ValidateTestClass();
        validateTestClass .setReason(12);
 
        validateTestClass .validateParams(); //调用验证的方法
    }
}


ok!这样就可以进行测试。

并且我们在使用的时候一定要注意,对于某一种验证规则是适用于一种数据类型的,简单说来,正则则表达式的验证对象可以为String类型的,但是不可以为Integer类型的数据,那么当我们使用正则表达式进行验证的时候就会出现错误。 
类似于:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Integer.
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.verifyResolveWasUnique(ConstraintValidatorManager.java:218)


意思就是你这个验证的注解不应该对该类型进行注解。

到此OK

 

1.2      SpringResource接口获取资源

http://elim.iteye.com/blog/2016305

 

关于我们 |  广告服务 |  联系我们 |  网站声明

Copyright © 2015 - 2016 DISPACE.NET |  使用帮助 |  关于我们 |  投诉建议

京ICP备13033209号-2