Springframework 1 - Overview

*** The following words, some are culled from Official Spring Framework Reference and some are summarized from my working practice.

Introduction

The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.

Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model
and tofull and partial Java EE.

Examples of how you, as an application developer, can benefit from the Spring platform:

  • MakeaJavamethodexecuteinadatabasetransactionwithouthavingtodealwithtransactionAPIs.
  • Make a local Java method a remote procedure without having to deal with remote APIs.
  • Make a local Java method a management operation without having to deal with JMX APIs.
  • Make a local Java method a message handler without having to deal with JMS APIs.

Modules

The Spring Framework consists of features organized into about 20 modules. These modules aregrouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),Instrumentation, Messaging, and Test, as
shown in the following diagram.

Core Container

The core container consists of:

spring-core,

spring-beans,

spring-context,

spring-context-support,

spring-expression (Spring Expression Language).

The Core andBeans (spring-core and spring-beans) modules provide the fundamental parts of the framework, including the IoC and Dependency Injection feature.

The Context (spring-context) module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry.

The Context module inherits its features from the Beans module and adds support forinternationalization (using, for example, resource bundles),
event propagation, resource loading, and
the transparent creation of contexts by
, for example, a Servlet container. The Context module also supportsJava EE features such as EJB, JMX, and basic remoting. The ApplicationContext interface is the focal point of the Context module.
spring-context-support provides support for integrating common third-party libraries into a Spring application context for caching (EhCache, Guava, JCache), mailing (JavaMail), scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports, Velocity).

The SpEL (spring-expression) module provides a powerful Expression Language for querying and manipulating an object graph at runtime. It is an extension of the unified expression
language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values, property assignment, method invocation, accessing the content of arrays, collections and indexers, logical and arithmetic operators,
named variables, and retrieval of objects by name from Spring’s IoC container. It also supports list projection and selection as well as common list aggregations.

AOP and Instrumentation

spring-aop

spring-aspacts

spring-instrument

spring-instrument-tomcat

Messaging

spring-messaging

Data Access / Integration

spring-jdbc, JDBC

spring-tx, transaction management

spring-orm, object-relational mapping

spring-oxm, Object/XML mapping

spring-jms, Java Messaging Service

Web

spring-web

spring-webmvc

spring-webmvc-portlet

spring-websocket

Test

spring-test

Maven Dependencies

GroupId ArtifactId Description

org.springframework


spring-aop


Proxy-based AOP support


org.springframework


spring-aspects


AspectJ based aspects


org.springframework


spring-beans


Beans support, including Groovy


org.springframework


spring-context


Application context runtime, including scheduling and remoting abstractions


org.springframework


spring-context-support


Support classes for integrating common third-party libraries into a Spring application context


org.springframework


spring-core


Core utilities, used by many other Spring modules


org.springframework


spring-expression


Spring Expression Language (SpEL)


org.springframework


spring-instrument


Instrumentation agent for JVM bootstrapping


org.springframework


spring-instrument-tomcat


Instrumentation agent for Tomcat


org.springframework


spring-jdbc


JDBC support package, including DataSource setup and JDBC access support


org.springframework


spring-jms


JMS support package, including helper classes to send and receive JMS messages


org.springframework


spring-messaging


Support for messaging architectures and protocols


org.springframework


spring-orm


Object/Relational Mapping, including JPA and Hibernate support


org.springframework


spring-oxm


Object/XML Mapping


org.springframework


spring-test


Support for unit testing and integration testing Spring components


org.springframework


spring-tx


Transaction infrastructure, including DAO support and JCA integration


org.springframework


spring-web


Web support packages, including client and web remoting


org.springframework


spring-webmvc


REST Web Services and model-view-controller implementation for web applications


org.springframework


spring-webmvc-portlet


MVC implementation to be used in a Portlet environment


org.springframework


spring-websocket


WebSocket and SockJS implementations, including STOMP support

Maven "Bill Of Materials" Dependency

It is possible to accidentally mix different versions of Spring JARs when using Maven. For example, you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older
release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency. You can import the spring-framework-bom in
yourdependencyManagement section
to ensure that all spring dependencies (both direct and transitive) are at the same version.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.1.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

An added benefit of using the BOM is that you no longer need to specify the <version> attribute
when depending on Spring Framework artifacts:

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

Logging

Logging 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 are using, and c) Spring integrates with lots of other tools all of which have also made a choice of logging dependency. One of the goals of an application developer is often to have unified
logging configured in a central place for the whole application, including all external components. This is more difficult than it might have been since there are so many choices of logging framework.

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We compile against JCL and we also make JCL Log objects
visible for classes that extend the Spring Framework. It’s important to users that all versions of Spring use the same logging library: migration is easy because backwards compatibility is preserved even with applications that extend Spring. The way we do
this is to make one of the modules in Spring depend explicitly on commons-logging(the
canonical implementation of JCL), and then make all the other modules depend on that at compile time. If you are using Maven for example, and wondering where you picked up the dependency on commons-logging,
then it is from Spring and specifically from the central module called spring-core.

The nice thing about commons-logging is
that you don’t need anything else to make your application work. It has a runtime discovery algorithm that looks for other logging frameworks in well known places on the classpath and uses one that it thinks is appropriate (or you can tell it which one if
you need to). If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short). You should find that your Spring application works and logs happily to the console out of the box in most situations, and that’s
important.

Not Using Commons Logging

Unfortunately, the runtime discovery algorithm in commons-logging,
while convenient for the end-user, is problematic. If we could turn back the clock and start Spring now as a new project it would use a different logging dependency. The first choice would probably be the Simple Logging Facade for Java ( SLF4J),
which is also used by a lot of other tools that people use with Spring inside their applications.

There are basically two ways to switch off commons-logging:

  1. Exclude the dependency from the spring-core module
    (as it is the only module that explicitly depends on commons-logging)
  2. Depend on a special commons-logging dependency
    that replaces the library 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>4.1.6.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

Now this application is probably broken because there is no implementation of the JCL API on the classpath, so to fix it a new one has to be provided. In the next section we show you how to provide an alternative
implementation of JCL using SLF4J as an example.

Using SLF4J

SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because
it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates. This also means that you have to be more explicit about what you want to happen at runtime, and declare it or configure it accordingly. SLF4J provides
bindings to many common logging frameworks, so you can usually choose one that you already use, and bind to that for configuration and management.

SLF4J provides bindings to many common logging frameworks, including JCL, and it also does the reverse: bridges between other logging frameworks and itself. So to use SLF4J with Spring you need to replace the commons-logging dependency
with the SLF4J-JCL bridge. Once you have done that then logging calls from within Spring will be translated into logging calls to the SLF4J API, so if other libraries in your application use that API, then you have a single place to configure and manage logging.

A common choice might be to bridge Spring to SLF4J, and then provide explicit binding from SLF4J to Log4J. You need to supply 4 dependencies (and exclude the existing commons-logging):
the bridge, the SLF4J API, the binding to Log4J, and the Log4J implementation itself. In Maven you would do that like this

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.6.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.5.8</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.8</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.8</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>

That might seem like a lot of dependencies just to get some logging. Well it is, but it is optional, and it should behave better than the vanilla commons-logging with
respect to classloader issues, notably if you are in a strict container like an OSGi platform. Allegedly there is also a performance benefit because the bindings are at compile-time not runtime.

A more common choice amongst SLF4J users, which uses fewer steps and generates fewer dependencies, is to bind directly to Logback.
This removes the extra binding step because Logback implements SLF4J directly, so you only need to depend on two libraries not four ( jcl-over-slf4j and logback).
If you do that you might also need to exclude the slf4j-api dependency from other external dependencies (not Spring), because you only want one version of that API on the classpath.

Using Log4J

Many people use Log4j as a logging framework for configuration and
management purposes. It’s efficient and well-established, and in fact it’s what we use at runtime when we build and test Spring. Spring also provides some utilities for configuring and initializing Log4j, so it has an optional compile-time dependency on Log4j
in some modules.

To make Log4j work with the default JCL dependency ( commons-logging)
all you need to do is put Log4j on the classpath, and provide it with a configuration file (log4j.properties or log4j.xml in
the root of the classpath). So for Maven users this is your dependency declaration:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>

And here’s a sample log4j.properties for logging to the console:

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n

log4j.category.org.springframework.beans.factory=DEBUG

Runtime Containers with Native JCL

Many people run their Spring applications in a container that itself provides an implementation of JCL. IBM Websphere Application Server (WAS) is the archetype. This often causes problems, and unfortunately there
is no silver bullet solution; simply excluding commons-logging from
your application is not enough in most situations.

To be clear about this: the problems reported are usually not with JCL per se, or even with commons-logging:
rather they are to do with binding commons-logging to
another framework (often Log4J). This can fail because commons-logging changed
the way they do the runtime discovery in between the older versions (1.0) found in some containers and the modern versions that most people use now (1.1). Spring does not use any unusual parts of the JCL API, so nothing breaks there, but as soon as Spring
or your application tries to do any logging you can find that the bindings to Log4J are not working.

In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container. That option isn’t always
open, but there are plenty of other suggestions in the public domain for alternative approaches, and your mileage may vary depending on the exact version and feature set of the container.

时间: 2024-10-03 18:50:00

Springframework 1 - Overview的相关文章

Spring Task Scheduler - No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined

1. Overview In this article, we are discussing the Springorg.springframework.beans.factory.NoSuchBeanDefinitionException – this is a common exception thrown by the BeanFactory when trying to resolve a bean that simply isn’t defined in the Spring Cont

java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext.getEnvironment()Lorg/springframework/core/env/ConfigurableEnvironment;问题

在springsecurity学习中,在加入spring有关的jar包后,出现java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext.getEnvironment()Lorg/springframework/core/env/ConfigurableEnvironment报错 出错原因:jar包版本有冲突 解决方法:换不同版本的jar包就可以解决问题了

ClassNotFoundException: org.springframework.web.se

信息: Starting Servlet Engine: Apache Tomcat/6.0.322012-3-31 9:39:40 org.apache.catalina.core.StandardContext listenerStart严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListenerjava.lang.ClassNotFoundE

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors

最近在项目中发现如下异常: 六月 25, 2015 5:58:34 下午 org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() for servlet springMVC threw exceptionorg.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult

java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener问题解决

今天搭建SSH项目的时候出现了例如以下错误: 严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener 网上查了一下.有些人说是没有spring的相关包.可是我检查这个包

maven 项目出现 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

maven 导入项目中经常出现这个问题 严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener 在网上找了些资料,有的说是少jar包,把有关spring的jar包复制到

springsecurity启动出现org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You must use a 3.0 schema with Spring Security 3.0.

在换了spring-security的jar包以后启动出现org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You must use a 3.0 schema with Spring Security 3.0.Please update your schema declarations to the 3.0.3 schema (spring-securi

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named &#39;App&#39; is defined

工具:Eclipse mars 环境:jdk1.8 说明:这是在学习Spring Task时遇到的一个bug,代码如下: 定时任务类: package com.task.test; import java.util.Date; import org.springframework.stereotype.Component; @Component public class App { public void execute1(){ System.out.printf("Task: %s, Curr

[spring-framework]Spring定时器的配置和使用

开发中我们常常会做一些定时任务,这些任务有开始时间,并会按一定的周期或规则执行.如此我们在Java程序开发中使用定时器来处理定时任务. <!-- MessageRequestTask类中包含了msgRequest方法,用于执行定时任务 --> <bean id="msg_request" class="com.santorini.task.timer.MessageRequestTask"></bean> <!-- 定时器配