Spring Source Code Analysis-interface and abstract class analysis for Resource access, springresource

Source: Internet
Author: User

Spring Source Code Analysis-interface and abstract class analysis for Resource access, springresource

Starting from today, we have taken a step-by-step approach to source code analysis. At the beginning, you must start with something simple. Let's start with Spring, and its Resource abstract interface Resource, the most powerful framework in the development history of Java.

I have read a lot of Spring source code analysis. At the beginning, Spring typical modules such as Spring IOC, AOP, and BeanFactory are annoying. These are for the time being. My idea is to analyze what others have not analyzed, or analyze what others have analyzed from different angles.

Many programmers who have used Spring for many years may have limited knowledge about resources. After all, accessing resources is generally a matter of building a web engineering framework. But it is also very beneficial to understand it.

This interface makes it easier for us to manipulate underlying resources. Because JDK basically controls underlying resources such as java.net. URL, java. io. File, and java. util. Properties. Retrieving resources is based on the absolute path or the relative path of the current class. It is not convenient to obtain resources from the classless path or Web Container context. The Resource interface provides more powerful access to underlying resources.

Let's talk a little bit about it. Let's take a look at the Resource class structure before looking at the source code.

I. Class Structure

I. Resource Interface

The Resouce interface is not a root interface. It inherits a simple parent interface, InputStreamSource, which has only one method to return an input stream:

InputStream getInputStream() throws IOException;

Come on, go directly to the source code of the Resource interface. I translated the Chinese language according to the English notes, as shown below:

Public interface Resource extends InputStreamSource {boolean exists (); // whether the Resource exists boolean isReadable (); // whether the Resource is readable boolean isOpen (); // whether the handle represented by the resource is opened by a stream URL getURL () throws IOException; // The handle URI getURI () throws IOException of the returned resource URL; // return the resource URI handle File getFile () throws IOException; // return the resource's File handle long contentLength () throws IOException; // The length of the resource content long lastModified () throws IOException; // The last modification time of the Resource: Resource createRelative (String relativePath) throws IOException; // create a new Resource String getFilename () based on the relative path of the Resource (); // resource file name String getDescription (); // Resource Description}

There's nothing to say. Continue!

 

Ii. abstract class AbstractResource

For any interface, this direct abstract class is the top priority, which concentrates most of the public implementations of the interface. After Translation:

Public abstract class implements actresource implements Resource {public boolean exists () {// checks whether the file exists. If an exception occurs in the process (because SecurityManager is called to determine whether the file exists ), close the corresponding stream try {return getFile (). exists ();} catch (IOException ex) {try {InputStream is = getInputStream (); // The getInputStream () method will be overwritten by the quilt class, is. close (); return true;} catch (Throwable isEx) {return false ;}} public boolean isReadable () {// return true directly, read return true ;} Public boolean isOpen () {// return false directly. return false is not enabled;} public URL getURL () throws IOException {// rewrite throw new FileNotFoundException (getDescription () for the subclass () + "cannot be resolved to URL");} public URI getURI () throws IOException {// return url URL url = getURL (); try {return ResourceUtils. toURI (url); // format the url and return} catch (URISyntaxException ex) {throw new NestedIOException ("Invalid URI [" + url + "]", Ex) ;}} public File getFile () throws IOException {// rewrite throw new FileNotFoundException (getDescription () for the subclass () + "cannot be resolved to absolute file path");} // The length of the resource content is actually the length of the resource byte, which can be determined by reading it all. This method occupies resources! Public long contentLength () throws IOException {InputStream is = this. getInputStream (); Assert. state (is! = Null, "resource input stream must not be null"); // asserted try {long size = 0; byte [] buf = new byte [255]; int read; while (read = is. read (buf ))! =-1) {size + = read;} return size;} finally {try {is. close () ;}catch (IOException ex) {}} public long lastModified () throws IOException {// return the last modification time of the resource long lastModified = getFileForLastModifiedCheck (). lastModified (); if (lastModified = 0L) {throw new FileNotFoundException (getDescription () + "cannot be resolved in the file system for resolving its last-modified timestamp ");} return lastModified;} // This is a method not available in the Resource interface. The comment indicates "returning a file, checking the timestamp", and the subclass must be rewritten... protected File getFileForLastModifiedCheck () throws IOException {return getFile ();} public Resource createRelative (String relativePath) throws IOException {// Leave It To The subclass to override throw new FileNotFoundException ("Cannot create a relative resource for" + getDescription ();} public String getFilename () {// null is returned by default (assuming the resource has no file name), unless the subclass overwrites return null;} @ Override public String toString () {// toString return the file description return getDescription ();} @ Override public boolean equals (Object obj) {// equals compares the two Resource descriptions for the same return (obj = this | (obj instanceof Resource & (Resource) obj ). getDescription (). equals (getDescription ();} @ Override public int hashCode () {// return the HashCode return getDescription () of the Resource description (). hashCode ();}}

 

Conclusion:

1. added a method, protected File getFileForLastModifiedCheck () throws IOException, which requires subclass implementation. If the subclass is not implemented, the resource File is directly returned. The specific function of this method is described later in the implementation class.

2. The contentLength () method is a heavyweight method. It reads all resources to determine the number of bytes of the resource. 255 bytes of buffer array to read. Subclasses are generally overwritten. (Adjust the buffer array size ?)

3. getDescription () is the only interface method that is not implemented in this abstract class. It is left to the subclass for implementation. The default equals () and hashCode () of the resource file are determined by this method.

4. The unique method getInputStream () of InputStreamSource is not implemented and left to the subclass.

 

Iii. Resource sub-interfaces ContextResource and WritableResource

These two interfaces inherit from Resource and have all the methods of Resource. The ContextResource interface adds a method:

String getPathWithinContext (); // return the path in the context.

This method enables its implementation class to return the current context path.

 

The WritableResource interface adds two methods:

Boolean isWritable (); // whether OutputStream getOutputStream () throws IOException can be written; // return the write stream of the Resource

This method enables its implementation class to write resources.

 

PS: the framework is like this. It is not difficult and the design model is not used much. But there is a kind of feeling of no work, no front, because the use of code is really very concise.

By analyzing the source code, you can also read your English documents to a large extent. Mutual encouragement.

 


Spring integrated hibernate and wrote a small program. Which of the following problems can I analyze?

DataSource
?? No such bean?

What is the basic principle of the ssh framework?

How Struts works

MVC, short for Model-View-Controller, is a common design pattern. MVC weakens the coupling between the business logic interface and the data interface, and makes the view layer more changeable. The working principle of MVC is shown in 1:
Struts is an implementation of MVC. It uses Servlet and JSP tags (belonging to the J2EE specification) as part of the implementation. Struts inherits various MVC features and makes corresponding changes and extensions based on J2EE features. How Struts works,

View: The view is mainly generated by JSP pages. Struts provides a wide range of JSP tag libraries, such as Html, Bean, Logic, and Template. This facilitates separate presentation of Logic and program Logic.

Control: In Struts, the Controller role in MVC is a Servlet called ActionServlet. ActionServlet is a common control component. This control component provides an entry point for processing all HTTP requests sent to Struts. It intercepts and distributes these requests to the corresponding response class (these response classes are subclasses of the Action class ). In addition, the control component is also responsible for filling the Action From (usually called FromBean) with the corresponding request parameters and passing them to the Action class (usually called ActionBean ). The logging class implements the core business logic. It can access java Beans or call ejbs. Finally, the controls class passes control to the subsequent JSP file, which generates a view. All of these control logics are configured using Struts-config.xml files.

Model: The model exists in the form of one or more java Beans. These beans are divided into three types: Action Form, Action, JavaBean or EJB. Action Form is generally called FormBean, which encapsulates user request information from the Client, such as Form information. Action is usually called ActionBean. It gets the FormBean from ActionSevlet, retrieves the relevant information in FormBean, and makes relevant processing. Generally, it calls Java Bean or EJB.

Process: In Struts, user requests are generally set *. do is used as the request service name, all *. do requests are directed to ActionSevlet, which encapsulates user requests into a FormBean with a specified name based on the configuration information in the Struts-config.xml and transmits this FormBean to the ActionBean with the specified name, actionBean performs business operations, such as file operations and database operations. Each *. do has a corresponding FormBean name and ActionBean name, which are configured in the Struts-config.xml.

Core: the Core of Struts is ActionSevlet, the core of ActionSevlet is Struts-config.xml.
Struts advantages and disadvantages

Advantages:
1. Open-source software provides a deeper understanding of its internal implementation mechanism.
2. The Taglib library can be used flexibly to greatly improve development efficiency.

3. page navigation makes the context of the system clearer. With a configuration file, you can grasp the relationship between all parts of the system, which is of great benefit for later maintenance. This advantage is especially evident when another group of developers take over the project.

4. Provides the Exception handling mechanism.
5. Database Connection Pool Management

6. Struts Action must be thread-safe. It only allows one instance to process all requests. Therefore, all resources used by action must be synchronized in a unified manner, which causes thread security issues.
Disadvantages:
Taglib is a major advantage of Struts, but for beginners, it requires a continuous learning process and even disrupt the habit of writing web pages. However, when you get used to it, you ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.