我们知道,在spring中,配置文件是通过资源形式加载的,我们首先来分析一些在spring中资源类的结构,并且查看一下资源的类型;
资源类图如下:
public interface InputStreamSource { /** * Return an {@link InputStream}. * <p>It is expected that each call creates a <i>fresh</i> stream. * <p>This requirement is particularly important when you consider an API such * as JavaMail, which needs to be able to read the stream multiple times when * creating mail attachments. For such a use case, it is <i>required</i> * that each <code>getInputStream()</code> call returns a fresh stream. * @throws IOException if the stream could not be opened * @see org.springframework.mail.javamail.MimeMessageHelper#addAttachment(String, InputStreamSource) */ InputStream getInputStream() throws IOException; }
抽象出这层接口,事实上是把java底层的二进制流和spring中的resource给对应以来,把inputstream包装进Resource;
public interface Resource extends InputStreamSource {
/**
* Return whether this resource actually exists in physical form.
* <p>This method performs a definitive existence check, whereas the
* existence of a <code>Resource</code> handle only guarantees a
* valid descriptor handle.
*/
boolean exists();
/**
* Return whether the contents of this resource can be read,
* e.g. via {@link #getInputStream()} or {@link #getFile()}.
* <p>Will be <code>true</code> for typical resource descriptors;
* note that actual content reading may still fail when attempted.
* However, a value of <code>false</code> is a definitive indication
* that the resource content cannot be read.
*/
boolean isReadable();
/**
* Return whether this resource represents a handle with an open
* stream. If true, the InputStream cannot be read multiple times,
* and must be read and closed to avoid resource leaks.
* <p>Will be <code>false</code> for typical resource descriptors.
*/
boolean isOpen();
/**
* Return a URL handle for this resource.
* @throws IOException if the resource cannot be resolved as URL,
* i.e. if the resource is not available as descriptor
*/
URL getURL() throws IOException;
/**
* Return a URI handle for this resource.
* @throws IOException if the resource cannot be resolved as URI,
* i.e. if the resource is not available as descriptor
*/
URI getURI() throws IOException;
/**
* Return a File handle for this resource.
* @throws IOException if the resource cannot be resolved as absolute
* file path, i.e. if the resource is not available in a file system
*/
File getFile() throws IOException;
/**
* Determine the content length for this resource.
* @throws IOException if the resource cannot be resolved
* (in the file system or as some other known physical resource type)
*/
long contentLength() throws IOException;
/**
* Determine the last-modified timestamp for this resource.
* @throws IOException if the resource cannot be resolved
* (in the file system or as some other known physical resource type)
*/
long lastModified() throws IOException;
/**
* Create a resource relative to this resource.
* @param relativePath the relative path (relative to this resource)
* @return the resource handle for the relative resource
* @throws IOException if the relative resource cannot be determined
*/
Resource createRelative(String relativePath) throws IOException;
/**
* Return a filename for this resource, i.e. typically the last
* part of the path: for example, "myfile.txt".
*/
String getFilename();
/**
* Return a description for this resource,
* to be used for error output when working with the resource.
* <p>Implementations are also encouraged to return this value
* from their <code>toString</code> method.
* @see java.lang.Object#toString()
*/
String getDescription();
}
抽象出来的Resource功能接口对于下面多种不同类型的资源,其有很多功能接口的实现势必是相同的,所以在这里spring建立了一个抽象类,在设计模式中,抽象类应该做到的是,尽量把子类相同的功能方法放到抽象父类中实现,增加复用,而尽量把少的数据推到子类中实现,减少空间的消耗;
在这类Resource中,我们使用得最多的,估计就是要属于ClassPathResource和FileSystemReource;顾名思意,这两种资源类分别是默认在ClassPath和FileSystem下查找资源;而我们用得最多的是classPath,因为这样对工程的移植更有利;
public class ClassPathResource extends AbstractFileResolvingResource {
private final String path;
private ClassLoader classLoader;
private Class<?> clazz;
/**
* Create a new ClassPathResource for ClassLoader usage.
* A leading slash will be removed, as the ClassLoader
* resource access methods will not accept it.
* <p>The thread context class loader will be used for
* loading the resource.
* @param path the absolute path within the class path
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see org.springframework.util.ClassUtils#getDefaultClassLoader()
*/
public ClassPathResource(String path) {
this(path, (ClassLoader) null);
}
/**
* Create a new ClassPathResource for ClassLoader usage.
* A leading slash will be removed, as the ClassLoader
* resource access methods will not accept it.
* @param path the absolute path within the classpath
* @param classLoader the class loader to load the resource with,
* or <code>null</code> for the thread context class loader
* @see java.lang.ClassLoader#getResourceAsStream(String)
*/
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
/**
* Create a new ClassPathResource for Class usage.
* The path can be relative to the given class,
* or absolute within the classpath via a leading slash.
* @param path relative or absolute path within the class path
* @param clazz the class to load resources with
* @see java.lang.Class#getResourceAsStream
*/
public ClassPathResource(String path, Class<?> clazz) {
Assert.notNull(path, "Path must not be null");
this.path = StringUtils.cleanPath(path);
this.clazz = clazz;
}
/**
* Create a new ClassPathResource with optional ClassLoader and Class.
* Only for internal usage.
* @param path relative or absolute path within the classpath
* @param classLoader the class loader to load the resource with, if any
* @param clazz the class to load resources with, if any
*/
protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
this.path = StringUtils.cleanPath(path);
this.classLoader = classLoader;
this.clazz = clazz;
}
/**
* Return the path for this resource (as resource path within the class path).
*/
public final String getPath() {
return this.path;
}
/**
* Return the ClassLoader that this resource will be obtained from.
*/
public final ClassLoader getClassLoader() {
return (this.classLoader != null ? this.classLoader : this.clazz.getClassLoader());
}
/**
* This implementation checks for the resolution of a resource URL.
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public boolean exists() {
URL url;
if (this.clazz != null) {
url = this.clazz.getResource(this.path);
}
else {
url = this.classLoader.getResource(this.path);
}
return (url != null);
}
/**
* This implementation opens an InputStream for the given class path resource.
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see java.lang.Class#getResourceAsStream(String)
*/
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else {
is = this.classLoader.getResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(
getDescription() + " cannot be opened because it does not exist");
}
return is;
}
/**
* This implementation returns a URL for the underlying class path resource.
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public URL getURL() throws IOException {
URL url;
if (this.clazz != null) {
url = this.clazz.getResource(this.path);
}
else {
url = this.classLoader.getResource(this.path);
}
if (url == null) {
throw new FileNotFoundException(
getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
}
/**
* This implementation creates a ClassPathResource, applying the given path
* relative to the path of the underlying resource of this descriptor.
* @see org.springframework.util.StringUtils#applyRelativePath(String, String)
*/
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new ClassPathResource(pathToUse, this.classLoader, this.clazz);
}
/**
* This implementation returns the name of the file that this class path
* resource refers to.
* @see org.springframework.util.StringUtils#getFilename(String)
*/
@Override
public String getFilename() {
return StringUtils.getFilename(this.path);
}
/**
* This implementation returns a description that includes the class path location.
*/
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
if (this.clazz != null) {
builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
builder.append('/');
}
builder.append(this.path);
builder.append(']');
return builder.toString();
}
/**
* This implementation compares the underlying class path locations.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ClassPathResource) {
ClassPathResource otherRes = (ClassPathResource) obj;
return (this.path.equals(otherRes.path) &&
ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) &&
ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz));
}
return false;
}
/**
* This implementation returns the hash code of the underlying
* class path location.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
}
是将//tihuan成/的代码,我们可见,在这段代码中,对传入的参数进行了严密的验证,正如代码大全中所介绍的防御性编程,我们假定从public传入进来的参数都是不安全的,只有在私有方法中,我们才对传入的参数不进行合法验证;
在这里,我们很明显的看出,代码中使用了适配器模式中的类适配器,在新的接口中,我们用resource接口包装了File,
在新的接口中,我们依然能访问file的isExist方法,却丝毫不知道我们是用的file;
其中,StrigUtils类是一个工具,他对path进行了预处理,处理了如//分解符和. ..等文件路径描述的特殊操作符
另外的byte等资源,跟bye和ByteInputeStream的关系是类似的,分别是把不同源的数据当作资源,不过ClasspathResource不同的是,你可以传入ClassLoader或者Class来制定当前的类加载器,从而可以确定资源文件的BascDir
如果你不制定classLoader的话和Class的话,那么就会默认是当前线程的ClassLoader,而在这里,PATH和ClassLoader的预处理,都是经过了一个工具类来进行的,可以,在总段代码中,我们看见了很多的复用性和组织性,很多细节的方面的值得我们效仿和学习
相关推荐
在使用spring-boot-starter-parent时,开发者可以通过配置Java版本、编码和源代码相关的设置来覆盖默认的配置。例如,开发者可以在pom.xml文件中添加以下配置来指定Java版本: <java.version>1.8 spring-boot-...
- `<source>` 和 `<target>`:这两个元素指定了Java源代码和目标代码的版本,这里都设置为1.8。 - `<encoding>`:指定源代码文件的编码格式,这里设置为UTF-8。 - `<compilerArguments>`:这里的`<extdirs>`元素...
- `spring-data-hadoop-2.2.0.RELEASE-sources.jar`:提供源代码,便于开发者查看和学习Spring Data Hadoop的实现细节,包括各种抽象类、接口和工具类。 4. **应用场景**: - 大数据分析:Spring Data Hadoop可以...
1. 添加依赖:首先,你需要在项目的pom.xml文件中引入Spring和MyBatis的依赖库,包括spring-context、spring-jdbc、mybatis、mybatis-spring等。 2. 配置数据源:在Spring的配置文件中,定义数据源(DataSource),...
通过这些章节的源代码学习,读者可以逐步掌握JSP技术,构建动态Web应用,并为后续深入学习Spring MVC、Struts等高级框架打下坚实的基础。实践是检验真理的唯一标准,结合理论与代码实践,将是提升JSP技能的最佳途径...
- 源代码:实现OAuth2协议的各种类和接口。 - 示例:展示如何配置和使用Spring Security OAuth2的示例项目。 - 测试:单元测试和集成测试,用于验证框架的正确性。 - 文档:关于框架使用的文档和API参考。 理解...
3. **spring-security-oauth2-2.0.3.RELEASE-sources.jar**:这是源码JAR文件,包含Spring Security OAuth2的原始源代码。对于开发者来说,这是一个宝贵的资源,因为他们可以直接查看和学习库的内部工作原理,调试...
Sparklr2和Tonr2的源代码提供了以下几个关键知识点: - **OAuth2的基本流程**:包括授权请求、授权码的获取、令牌的交换以及资源的获取等步骤。 - **Spring Security OAuth2组件**:例如`AuthorizationServer`...
Spring框架的源代码分析主要集中在它的核心特性——控制反转(IOC)容器上。IOC容器是Spring的核心组件,它负责管理应用程序中的对象,也就是所谓的"bean"。BeanFactory接口是IOC容器的基础,它定义了最基础的bean...
`Resource`接口是Spring框架提供的一种抽象层,用于封装资源访问,它可以是本地文件系统中的文件,也可以是URL、类路径下的资源,甚至是JDBC数据源。通过`Resource`接口,开发者可以统一地处理不同来源的资源,提高...
Spring Boot 是一个基于 Spring 框架的快速开发工具,它简化了创建独立的、生产级别的基于 Spring 应用的步骤。JSP(JavaServer Pages)是 Java 平台上用于构建动态网页的一种技术。在 Spring Boot 中,默认并不支持...
2. `src/main/java`:源代码目录,包含了服务端点、控制器、过滤器、配置类和其他业务逻辑。 3. `src/main/resources`:资源文件,可能包含配置文件如`application.yml`或`application.properties`,用于配置Spring ...
Spring框架的源代码解析主要集中在它的核心特性——依赖注入(Dependency Injection,简称DI),这是通过Inversion of Control(IOC)容器实现的。IOC容器在Spring中扮演着至关重要的角色,负责管理对象(bean)的...
源代码涵盖了第二至第六章的内容,这五个章节分别涉及了Spring的基础、依赖注入、AOP(面向切面编程)、事务管理和Web应用等方面的知识。以下是这些章节的关键知识点详解: 1. **第二章:Spring概述** - Spring...
### Spring源代码自我解析 #### 一、Spring框架概述与价值 Spring框架作为一个全面的轻量级企业级应用开发框架,其设计精妙且结构清晰,不仅展现了设计者Rod Johnson等人的深厚技术功底,同时也成为了Java技术领域...
import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; @...
通过理解和掌握Spring的Resource管理,我们可以更加灵活、高效地处理各种资源,提高代码的可维护性和可扩展性。在实际开发中,合理利用Resource接口及其实现,可以显著提升资源访问的便捷性和一致性。
通过分析这些源码,我们可以深入理解OAuth的工作原理,以及Spring Security OAuth如何支持这些功能。同时,Sparklr2和Tonr2示例能帮助我们直观地看到OAuth流程的每个步骤,包括授权、令牌交换和资源访问。 在实际...
在Java中,注解是一种元数据,它提供了在源代码中附加信息的方式。Spring框架支持多种注解,如`@Autowired`、`@Qualifier`、`@Resource`等,用于实现依赖注入。 1. `@Autowired`注解:这是Spring中最常用的注解,...
1. `src/main/java`: 存放项目的 Java 源代码,包括 Spring Security 配置类和其他相关服务。 2. `src/main/resources`: 包含配置文件,如 `application.properties` 或 `application.yml`,以及可能的静态资源。 3....