Spring Framework Reference Manual _5.0.0_ Chinese version _part i_ chapter II __spring

Source: Internet
Author: User
Tags aop naming convention web services maven central log4j

Article Author: Tyan
Blog: noahsnail.com
More Spring framework content is available to the author blog for continuous updates. 2.Spring Framework Introduction

The spring framework is a Java platform that provides a comprehensive infrastructure for supporting the development of Java applications. Spring processes the infrastructure so you can focus on your application.

Spring enables you to create simple Java objects (POJO) and to apply Enterprise Services to Simple Java Objects (POJO) in a non-invasive style.

As an application developer, here are some examples you can benefit from the spring platform:
* Execute a Java method in a database business without having to deal with business APIs
* Enables a local Java method to be invoked remotely without having to deal with remote APIs
* Make a local Java method into a management operation without having to deal with JMX APIs
* Make a local Java method a message processor without having to deal with JMS APIs 2.1 Dependency Injection and control reversal

Java application--an imprecise term that can represent both restricted embedded applications and the enterprise-level applications of N-tier services-typically composed of many objects that collaborate to form a complete application. Therefore, objects in an application are interdependent .

Although the Java platform provides a wide range of application development capabilities, it lacks the means to organize these basic building blocks into a coherent whole and leaves the task of organizing the basic building blocks to architects and developers. Although you can use design patterns such as Factory mode, abstract Factory mode, generator pattern, decoration mode, service positioning mode to create various classes and object instances that make up the application, these design patterns are simple: named best practices, role descriptions of patterns, location of application patterns, Patterns to solve problems and so on. Patterns formalize best practices, which means you have to implement them yourself in your application.

The control inversion (IoC) component in the spring framework solves this problem by providing a formalized approach that creates different components into a complete, ready-to-use work application. The spring framework encodes formalized design patterns into the best objects you can integrate into your own applications. Many organizations and agencies use the spring framework in this way to build robust, maintainable applications.

background
"The question is what is control reversal. "Martin Fowler on his website in 2004 raised this issue about control reversal (IoC). Fowler recommends renaming this principle to make it more visible and to provide dependency injection . 2.2 Module

The spring framework consists of approximately 20 modules. These modules can be grouped into core containers, data access/integration, WEB,AOP (aspect-oriented programming), devices, messages, and tests, as shown in the following illustration.

Figure 2.1 Spring Framework Overview

The following sections list the modules that are available for each feature, their artifact names, and the topics they contain. The artifact name is associated with the artifact IDs used in the dependency management tool. 2.2.1 Core Container

Core container features include Spring-core, Spring-beans, Spring-context, Spring-context-support, and spring-expression (Spring expression language) modules.

The Spring-core and Spring-beans modules provide the infrastructure component of the framework, including control inversion (IoC) and Dependency injection (DI) functionality. Beanfactory is a high-level implementation of the factory pattern. It removes the need for a program's single example pattern and allows you to decouple configuration and dependency designations from the actual program logic.

The context (Spring-context) module is built on a solid foundation provided by the core module and the Beans module: It is a way of accessing objects in a framework-style pattern similar to the Jndi registry. The context module inherits the functionality of the Beans module and adds support for internationalization (such as using resource bundles), event propagation, resource loading, and transparent creation of the context (for example, through the servlet container). The context module also supports Java EE features such as EJB,JMX and basic remote. The ApplicationContext interface is the focus of the context module. Spring-context-support supports the integration of Third-party libraries into the spring application context, especially caching (EhCache, Jcache) and timed execution (COMMONJ, Quartz). 2.2.2 Facet Programming (AOP) and devices (instrumentation)

The SPRING-AOP module provides an AOP alliance-compliant (AOP Federation)-oriented programming implementation, such as allowing you to customize the method interceptor and pointcut to clear decoupling function implementations should be separate code. With the source-level metadata feature, you can also incorporate behavioral information into your code, which in some ways is similar. NET's property values.

The independent Spring-aspects module provides integration with the ASPECTJ.

The Spring-instrument module provides class device support and class loader implementations that can be used in some application servers. The Spring-instrument-tomcat module contains the Tomcat Spring device agent. 2.2.3 Message

The Spring 4 framework contains the Spring-messaging module, which is for spring integration projects such as message, Messagechannel, MessageHandler and other projects that serve as the basis for Messaging application services are an important abstraction. The module also contains a series of annotations that map messages to methods, which are similar to the programming model Spring MVC annotations. 2.2.4 data access/integration

The data access/integration layer includes JDBC,ORM,OXM,JMS and transaction modules.

The SPRING-JDBC module provides a JDBC abstraction layer that does not require the writing of monotonous JDBC code to parse the error codes specified by the database provider.

The SPRING-TX module provides programmatic (programmatic) and declarative (declarative) business management for classes that implement the specified interface and all of the Simple Java Objects (POJOs).

The Spring-orm module provides an integrated layer of popular object-relational mapping APIs, including JPA and hibernate. When using the Spring-orm module, you can use the other features of spring in conjunction with these o/r-mapping frameworks, such as the simple declarative business management functions mentioned earlier.

The SPRING-OXM module provides an abstraction layer for object/xml mapping implementations such as JAXB,CASTOR,JIBX and XStream.

The SPRING-JMS module (Java Messaging Service) contains features that generate and process care. Starting with the Spring 4.1 framework, it provides integration with spring-messaging. 2.2.5 Network

The network layer contains Spring-web, SPRING-WEBMVC, and Spring-websocket modules.

The Spring-web module provides basic network-oriented integration features, such as the multipart File upload feature, using servlet listeners to initialize IOC containers and network-oriented application contexts. It also contains the network-related portions of the HTTP client and spring remote support.

The Spring-webmvc module (also known as the web-servlet module) contains the network application implementations of Spring's Model-view-controller (MVC) and rest Web services. Spring's MVC Framework provides a complete separation of the domain model code, Web Forms, and other features of the spring framework. 2.2.6 Test

The Spring-test module supports unit testing, spring components, and junit or testng integration tests. It provides the applicationcontexts load of spring and the consistency of these context caches. It also provides mock objects that can test the code separately. 2.3 Usage Scenarios

The building blocks described earlier make spring a reasonable choice in many scenarios, from running embedded applications that are constrained in resources to fully fledged enterprise applications using spring's business management capabilities and network framework integration.

Fig. 2.2 Standard Mature Spring Web application

Spring's declarative business management capabilities make Web applications fully transactional, and if you use EJB containers to manage your business, you'll find them essentially the same. All of your custom business logic can be implemented with POJOs and managed by spring's IOC container. Additional business includes support for mail delivery and validation, which is independent of the web layer, and you are free to choose where to validate the execution of the rule. Spring's support for ORM is integrated with JPA and hibernate, for example, when you use Hibernate, you can continue to use your existing mapping files and the standard hibernate sessionfactory configuration. Form controllers are seamlessly integrated into the Web layer and domain model, and for your domain model no longer requires actionforms or other classes that convert HTTP parameters to values.

Figure 2.3. Spring Mesosphere using a third-party web framework

Sometimes the environment doesn't allow you to completely turn into a different frame. The spring framework does not force you to adopt what is inside it; it is not a solution that is either all or nothing . The existing front-end built with STRUTS,TAPESTRY,JSF or other UI frameworks can be integrated with the spring-based middle tier, which allows you to use the business features of spring. You just need to simply bind your business logic with ApplicationContext and Webapplicationcontext and then integrate it into the web layer.

Figure 2.4. Remote Application Scenario

When you need to access existing code through a Web service, you can use spring's hessian-, rmi-, or Httpinvokerproxyfactorybean classes. This makes it easy to access existing applications remotely.

Figure 2.5. ejbs-Packaging of existing POJOs

The spring framework also provides access and abstraction layers for enterprise JavaBeans, enabling you to reuse your existing pojos, which can be packaged into stateless session beans for extensible use, and fail-safe Web applications may need to be declared secure. 2.3.1 Dependency Management and naming conventions

Dependency management and Dependency injection are two things that are completely different. To be able to use Spring's outstanding features in your application (like dependency injection), you need to collect all the necessary libraries (jar files) and add them to the classpath at run time, which may need to be added at compile time. These dependencies are not virtual builds to be injected, but physical resources in the file system (usually). These dependency management processes include locating, storing, and adding resources to classpath. Dependencies can be direct (for example: My application relies on spring at runtime), or indirectly (for example, my application relies on commons-dbcp, and it relies on commons-pool). Indirect dependencies are also referred to as "transitive", and these dependencies are also the hardest to identify and manage.

If you want to use spring, you need to have a copy of the jar library that contains the SPIRNG functionality you need. To make this easier, spring is packaged into a series of modules that, if you don't want to write web apps, will be separated as much as possible, so you don't need spring-web modules. To refer to Spring's library module in this guide, we used a shorthand naming convention spring-* or spring-*.jar,* to represent the abbreviated name of the module (for example, Spring-core, Spring-webmvc, SPRING-JMS, and so on). The actual jar file name you use is usually the module name plus the version number (for example, Spring-core-5.0.0.build-snapshot.jar).

Each release of the spring Framework will be published below artifacts:
* Maven Central,maven The default warehouse for queries and does not require any specific configuration when used. Many of the common libraries that spring relies on can also be obtained from MAVEN, a large part of the spring community using Maven for dependency management, so this is convenient for them. The name of the jar package is Spring-*-<version>.jar,maven GroupID is org.springframework.
* The Open Maven library, run by spring. In addition to the final GA release (publicly available version), the warehouse also has a developed version of the snapshot and milestone version. The jar package is named in the same way as Maven, which is a useful place to use the spring development version, while the other libraries are deployed in Maven. This library also contains bundled ZIP files that are bundled together to easily download all the spring jar packages in this zip file.

You will find the spring artifacts list below. For a more comprehensive description of each module, see section 2.2.

Table 2.1. Spring Framework Artifacts

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        < artifactid>spring-context</artifactid>
        <version>5.0.0.BUILD-SNAPSHOT</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

That's it. Note that if you do not need to compile the spring Apis,scope can be declared as Rumtime, this is a typical case of basic dependency injection.

The example above is used in the MAVEN central repository. In order to use the Spring Maven repository (for example: using the milestone version or the snapshot version), you need to specify the location of the warehouse in the MAVEN configuration, the full version:

<repositories>
    <repository>
        <id>io.spring.repo.maven.release</id>
        <url >http://repo.spring.io/release/</url>
        <snapshots><enabled>false</enabled></ snapshots>
    </repository>
</repositories>

For milestone version:

<repositories>
    <repository>
        <id>io.spring.repo.maven.milestone</id>
        < Url>http://repo.spring.io/milestone/</url>
        <snapshots><enabled>false</enabled> </snapshots>
    </repository>
</repositories>

For snapshot version:

<repositories>   
    <repository>
        <id>io.spring.repo.maven.snapshot</id>
        <url >http://repo.spring.io/snapshot/</url>
        <snapshots><enabled>true</enabled></ snapshots>
    </repository>
</repositories>

Maven "Bill of Materials" dependencies

When using MAVEN, it is possible to accidentally mix different versions of spring jars. For example, you might find a third-party library, or another spring project, that passes through dependencies into an older version. If you forget to explicitly declare a direct dependency, you will have a variety of unexpected problems.

To address this problem, MAVEN supports the concept of bill of materials (BOM) dependencies. You can import Spring-framework-bom in your dependencymanagement section to ensure that all spring dependencies (direct and transitive) are the same version.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId> org.springframework</groupid>
            <artifactId>spring-framework-bom</artifactId>
            < version>5.0.0.build-snapshot</version>
            <type>pom</type>
            <scope>import</ scope>
        </dependency>
    </dependencies>
</dependencyManagement>

The added benefit of using a BOM is that you no longer need to specify <version> attributes when you rely on the artifacts of the spring framework:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        < artifactid>spring-context</artifactid>
    </dependency>
    <dependency>
        <groupid >org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </ Dependency>
<dependencies>

Gradle Dependency Management

In order to use the Spring warehouse in the Gradle build system, the appropriate URLs need to be included in the repositories section:

repositories {
    mavencentral ()
    //and optionally ...
    Maven {URL "http://repo.spring.io/release"}
}

When appropriate, you can modify the repositories URL from/release to/milestone or/snapshot. Once a warehouse is configured, you can declare dependencies in the usual gradle way:

dependencies {
    compile ("Org.springframework:spring-context:5.0.0.build-snapshot")
    testcompile (" Org.springframework:spring-test:5.0.0.build-snapshot ")
}

Ivy Dependency Management

If you prefer to use Ivy to manage dependencies, this has a similar configuration option.

To configure Ivy to specify the Spring warehouse, add the following parser to your ivysettings.xml:

<resolvers>
    <ibiblio name= "io.spring.repo.maven.release"
            m2compatible= "true"
            root= "http://" repo.spring.io/release/"/>
</resolvers>

When appropriate, you can change the root URL from the repositories URL from/release to/milestone or/snapshot.

Once configured, you can add dependencies in a general way. For example (in Ivy.xml):

<dependency org= "Org.springframework" name= "Spring-core" rev= "5.0.0.build-snapshot" conf=
    Runtime "/>

Release zip file

Although using a build system that supports dependency management is the recommended way to get the spring framework, you can still download the release zip file.

The release of Zips is published to the spring Maven repository (this is just for our convenience and you don't need Maven or any other build system to download them).

To download the release zip, open the browser input http://repo.spring.io/release/org/springframework/spring, and then select the appropriate subfolder for the version you want. The release file ends with-dist.zip, such as Spring-framework-{spring-version}-release-dist.zip. Distributions can also publish milestone versions or snapshots versions. 2.3.2 Log

The log is a very important dependency for spring because: a It is the only mandatory external dependency, B) Everyone likes to see some output from the tools they use, *c) *spring integrates many other tools, and these tools also choose log Dependencies. One goal of the application developer is that for the entire application, there is often a central place for the unified configuration of the logs, including all external components. More difficult than it may be to have too many log frames to choose from.

Forced log dependency in spring is the Jakarta Commons Logging API (JCL). We compile the JCL and make the Jcllog object visible to the class, which extends the spring framework. All versions of spring use the same log library: porting is easy because it is important for users to have the application extend spring but retain backward compatibility. The way we do this is to make one of spring's modules explicitly dependent on commons-logging (JCL's standard implementation) and then make other modules rely on the module at compile time. For example, if you're using MAVEN, you want to find out where the dependencies depend on commons-logging, and it's in spring, or rather, in spring's central module Spring-core.

A good thing about commons-logging is to make your application work you don't need anything else. It has a run-time discovery algorithm that can look for other log frames in a well-known classpath and use one that it deems appropriate (or if you tell it what you want to use if you need it). If you can't find anything else, you can find a very beautiful log (java.util.logging or abbreviation for June) from the JDK. In most environments you can find that your spring application runs properly and outputs logs to the console output box, which is important.

do not use Commons Logging

Unfortunately, although Commons-logging's run-time discovery algorithm is convenient for end users, it is problematic. If we dial back the clock and restart spring as a new project, a different log dependency will be selected. The first option may be simple Logging façade for Java (SLF4J), and many other tools used by people using spring within the application are also slf4j.

There are two ways to turn off commons-logging: Excluding dependencies from the Spring-core module (because it is the only explicit dependency) the Commons-logging module relies on a particular commons-logging dependency, Replace this dependency with an empty jar (more details can be found in the SLF4J FAQ).

To exclude commons-logging, add the following to your dependencymanagement section:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        < artifactid>spring-core</artifactid>
        <version>5.0.0.BUILD-SNAPSHOT</version>
        < exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId> commons-logging</artifactid>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

This application may now be broken because there is no JCL API implementation in Classpath, and a new implementation must be provided to address this problem. In the next section we will show you how to provide a JCL alternative implementation, using SLF4J is an example.

using SLF4J

SLF4J is a purer dependency and is more efficient at run time than commons-logging because it uses compile-time binding instead of other log frames for runtime lookup integration. This also means that you have to be more aware of what happens when you want to run, and then declare it or configure it accordingly. SLF4J provides bindings to many common log frames, so you can usually choose a log frame that you are using, and then bind to configuration and management.

SLF4J provides bindings to many common log frames, including JCL, which does the opposite, creating other log frames and its own links. So in order to use SLF4J in spring, you need to replace commons-logging dependencies with SLF4J-JCL connectors. Once you have used log calls within spring, spring will change the log call to call the SLF4J API, and if the other libraries in your application call that API, you will have a separate place to configure and manage the logs.

A common choice is to connect spring and SLF4J, and then provide an explicit binding slf4j to log4j. You will need to provide four dependencies (excluding existing commons-logging): Connection, slf4j API, binding to log4j, log4j itself implementation. You might do this in Maven:

<dependencies> <dependency> <groupId>org.springframework</groupId> &LT;ARTIFAC Tid>spring-core</artifactid> <version>5.0.0.BUILD-SNAPSHOT</version> &LT;EXCLUSIONS&G
            T <exclusion> <groupId>commons-logging</groupId> <artifactid>commons -logging</artifactid> </exclusion> </exclusions> </dependency> &LT;DEP
        Endency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupid>org.slf4
    J</groupid> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactid>slf4 J-log4j12</artifactId> <version>1.5.8</version> </dependency> <dependency> &L T;groupid>log4j</groupid> <artifactId>log4j</artifactId> <version>1.2.14</ve Rsion> </dependency> </dependencies>

This may seem to require a lot of reliance in order to get some logs. Luckily it's optional, and it should be better than Commons-logging's problem with the ClassLoader, especially if you're in a container as stringent as the OSGi platform. It is said that there is also a performance boost because the bindings are at compile time and not at runtime.

A more general option for SLF4J users is to bind directly to Logback, which is less used and less dependent. This goes beyond the external binding step because Logback directly implements the SLF4J, so you only need to rely on two libraries instead of four (JCL-OVER-SLF4J and Logback). If you do this you may also need to exclude SLF4J-API dependencies from other external applications (not from spring), because you need only one version of the API in Classpath.

using log4j

Many people use log4j as the logging framework for configuration and management. It's effective and perfect, and when we build and test spring, it's actually what we use at runtime. Spring also provides some tools for configuring and initializing log4j, so that some modules have optional log4j compile-time dependencies.

To enable log4j to work with the default JCL dependency (commons-logging), all you need to do is put log4j in Classpath and provides a configuration file (Log4j.properties or log4j.xml in the classpath root directory). For MAVEN user dependencies the following declaration is as follows:

<dependencies> <dependency> <groupid>org.springframework</groupi 
    D> <artifactId>spring-core</artifactId> <version>5.0.0.BUILD-SNAPSHOT</version> </dependency> <dependency> <groupId>log4j</groupId> <arti 

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.