`

Spring 2.X 深入了解 ------->Resource操作和Validator

 
阅读更多

Spring的 Resource 接口是为了提供更强的访问底层资源能力的抽象。

 

Resource 接口一些比较重要的方法如下:

  • getInputStream() : 定位并打开资源,返回读取此资源的一个 InputStream 。每次调用预期会返回一个新的 InputStream ,由调用者负责关闭这个流。

  • exists() : 返回标识这个资源在物理上是否的确存在的 boolean 值。

  • isOpen() : 返回标识这个资源是否有已打开流的处理类的 boolean 值。如果为 true ,则此InputStream 就不能被多次读取,而且只能被读取一次然后关闭以避免资源泄漏。除了 InputStreamResource ,常见的resource实现都会返回 false

  • getDescription() : 返回资源的描述,一般在与此资源相关的错误输出时使用。此描述通常是完整的文件名或实际的URL地址。

Resource 作为属性来配置
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>

例子:
package com.chenhailong.resource;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;


/**
 * 
 * @author cnchenhl
 * Aug 22, 2011
 */
public class SpringResource {

    public static void main(String[] args) throws IOException {

        ApplicationContext cxt = new FileSystemXmlApplicationContext();
        Resource rs = cxt.getResource("1.txt");
        File file = rs.getFile();
        System.out.println(file.getAbsoluteFile());
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while (reader.ready()) {
            System.out.println(reader.readLine());
        }
        reader.close();
        ApplicationContext cxtClass = new ClassPathXmlApplicationContext();
        Resource template = cxtClass.getResource("classpath:1.txt");
        InputStream inputStream = template.getInputStream();
        BufferedReader readerClassStream = new BufferedReader(new InputStreamReader(inputStream));
        while (readerClassStream.ready()) {
            System.out.println(readerClassStream.readLine());
        }
        File fileClass = template.getFile();
        System.out.println(fileClass.getAbsolutePath());

        BufferedReader readerClass = new BufferedReader(new FileReader(file));
        while (readerClass.ready()) {
            System.out.println(readerClass.readLine());
        }
    }
}
 
Validator的使用:
package com.chenhailong.validator;

/**
 * @author cnchenhl
 * Aug 22, 2011
 */
public class Person {

    private String name;
    private int age;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

}
 
package com.chenhailong.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @author cnchenhl
 * Aug 22, 2011
 */
public class PersonValidator implements Validator {

    @Override
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);

    }

    @Override
    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 100) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}
 
package com.chenhailong.validator;

import java.util.List;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;

/**
 * @author cnchenhl
 * Aug 22, 2011
 */
public class SpringValidator {

    /**
     * @param args
     */
    public static void main(String[] args) {
        PersonValidator pv = new PersonValidator();
        Person person = new Person();
        person.setAge(-10);
        person.setName("");
        pv.supports(Person.class);
        Errors e = new BindException(person, "person");
        pv.validate(person, e);
        List list = e.getAllErrors();
        for (int i = 0; i < list.size(); i++) {

            System.out.println(((ObjectError) list.get(i)).getCode());
        }
    }

}
 
0
1
分享到:
评论

相关推荐

    spring-framework-reference-4.1.2

    What’s New in Spring Framework 4.x .................................................................................... 16 3. New Features and Enhancements in Spring Framework 4.0 .....................

    Spring-Reference_zh_CN(Spring中文参考手册)

    13.9.2. form标签 13.9.3. input标签 13.9.4. checkbox标签 13.9.5. radiobutton标签 13.9.6. password标签 13.9.7. select标签 13.9.8. option标签 13.9.9. options标签 13.9.10. textarea标签 13.9.11. hidden标签...

    spring-framework-reference4.1.4

    What’s New in Spring Framework 4.x .................................................................................... 16 3. New Features and Enhancements in Spring Framework 4.0 .....................

    spring chm文档

    13.11.2. 对模型的支持:ModelMap (ModelAndView) 13.11.3. 对视图的支持: RequestToViewNameTranslator 13.12. 其它资源 14. 集成视图技术 14.1. 简介 14.2. JSP和JSTL 14.2.1. 视图解析器 14.2.2. 'Plain-...

    Spring中文帮助文档

    13.9.2. form标签 13.9.3. input标签 13.9.4. checkbox标签 13.9.5. checkboxes标签 13.9.6. radiobutton标签 13.9.7. radiobuttons标签 13.9.8. password标签 13.9.9. select标签 13.9.10. option标签 ...

    Spring API

    11.7.2. 处理BLOB 和 CLOB对象 11.7.3. 在IN语句中传入一组参数值 11.7.4. 处理复杂类型的存储过程调用 12. 使用ORM工具进行数据访问 12.1. 简介 12.2. Hibernate 12.2.1. 资源管理 12.2.2. 在Spring容器中...

    Spring 2.0 开发参考手册

    13.9.2. form标签 13.9.3. input标签 13.9.4. checkbox标签 13.9.5. radiobutton标签 13.9.6. password标签 13.9.7. select标签 13.9.8. option标签 13.9.9. options标签 13.9.10. textarea标签 13.9.11. ...

    单点登录源码

    本系统是基于RBAC授权和基于用户授权的细粒度权限控制通用平台,并提供单点登录、会话管理和日志管理。接入的系统可自由定义组织、角色、权限、资源等。用户权限=所拥有角色权限合集+用户加权限-用户减权限,优先级...

    开源框架 Spring Gossip

    &lt;br&gt;第一个 Spring 程式 &lt;br&gt;BeanFactory、 ApplicationContext &lt;br&gt;Type 2 IoC、Type 3 IoC &lt;br&gt;属性参考 &lt;br&gt;自动绑定 &lt;br&gt;集合物件注入 &lt;br&gt;Bean 的生命周期 &lt;br&gt;Bean 进阶管理 &lt;br&gt;理想上对于 Bean 来说,它不...

    金蝶BOSV6.1_业务组件API参考手册

    com.kingdee.bos.appframework.validator com.kingdee.bos.cache com.kingdee.bos.cache.impl com.kingdee.bos.cache.impl.remote com.kingdee.bos.config com.kingdee.bos.config.app ...

    SPRING API 2.0.CHM

    ConnectionFactoryUtils.ResourceFactory ConnectionHandle ConnectionHolder ConnectionHolder ConnectionProxy ConnectionSpecConnectionFactoryAdapter ConnectorServerFactoryBean ConsoleListener ...

    Apache Wicket Cookbook.pdf

    Chapter 2: Getting Down and Dirty with Forms and Form Components 33 Introduction 33 Creating linked selectboxes 34 Composing multiple form components into a single reusable component 39 Preventing...

    odp-forseti-constraint-library:ODP团队的forseti约束库

    Dockerfile可用于构建具有必要二进制文件的映像,以开发和测试Terraform Validator约束。 发展约束 所有新的和将来的约束开发都应在约束文件夹内进行。 所有约束文件都是与它们共享字段kind的模板的“实例”。 ...

Global site tag (gtag.js) - Google Analytics