spring学习笔记(一)

1.2.spring Modules

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


Overview of the Spring Framework

1.2.1 Core Container

The Core Container consists of the Core, Beans, Context, and Expression Language modules.

The Core and Beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features. TheBeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

The Context module builds on the solid base provided by theCore 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 for internationalization (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 supports Java EE features such as EJB, JMX ,and basic remoting. TheApplicationContext interface is the focal point of the Context module.

The Expression Language 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 context 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 aggregation

1.2.2 Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popular object-relational mapping APIs, includingJPA,JDO, Hibernate, and iBatis. Using the ORM package you can use all of these O/R-mapping frameworks in combination with all of the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.

The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service (JMS) module contains features for producing and consuming messages.

The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and forall your POJOs (plain old Java objects).

1.2.3 Web

The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.

Spring's Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. It also contains the web-related parts of Spring's remoting support.

The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications. Spring's MVC framework provides a clean separation between domain model code and web forms, and integrates with all the other features of the Spring Framework.

The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application. Note that this support is now deprecated as of Spring 3.0. Consider migrating your application to Struts 2.0 and its Spring integration or to a Spring MVC solution.

The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.

1.2.4 AOP and Instrumentation

Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, you can also incorporate behavioral information into your code, in a manner similar to that of .NET attributes.

The separate Aspects module provides integration with AspectJ.

The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers.

1.2.5 Test

The Test module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use to test your code in isolation.


Maven Dependency Management

If you are using Maven for dependency management you don't even need to supply the logging dependency explicitly. For example, to create an application context and use dependency injection to configure an application, your Maven dependencies will look like this:

<dependencies>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.0.0.RELEASE</version>
      <scope>runtime</scope>
   </dependency>
</dependencies> 

That's it. Note the scope can be declared as runtime if you don't need to compile against Spring APIs, which is typically the case for basic dependency injection use cases.

We used the Maven Central naming conventions in the example above, so that works with Maven Central or the SpringSource S3 Maven repository. To use the S3 Maven repository (e.g. for milestones or developer snapshots), you need to specify the repository location in your Maven configuration. For full releases:

<repositories>
   <repository>
      <id>com.springsource.repository.maven.release</id>
      <url>http://repo.springsource.org/release/</url>
      <snapshots><enabled>false</enabled></snapshots>
   </repository>
</repositories>

For milestones:

<repositories>
   <repository>
      <id>com.springsource.repository.maven.milestone</id>
      <url>http://repo.springsource.org/milestone/</url>
      <snapshots><enabled>false</enabled></snapshots>
   </repository>
</repositories>

And for snapshots:

<repositories>
   <repository>
      <id>com.springsource.repository.maven.snapshot</id>
      <url>http://repo.springsource.org/snapshot/</url>
      <snapshots><enabled>true</enabled></snapshots>
   </repository>
</repositories>

1.3.2 Logging

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.

Switching off commons-logging is easy: just make sure it isn't on the classpath at runtime. In Maven terms you exclude the dependency, and because of the way that the Spring dependencies are declared, you only have to do that once.

<dependencies>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.0.0.RELEASE</version>
      <scope>runtime</scope>
      <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 thecommons-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 existingcommons-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-context</artifactId>
          <version>3.0.0.RELEASE</version>
          <scope>runtime</scope>
          <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>
          <scope>runtime</scope>
       </dependency>
       <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.5.8</version>
          <scope>runtime</scope>
       </dependency>
       <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.5.8</version>
          <scope>runtime</scope>
       </dependency>
       <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.14</version>
          <scope>runtime</scope>
       </dependency>
    </dependencies> 

That might seem like a lot of dependencies just to get some logging. Well it is, but itis optional, and it should behave better than the vanillacommons-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 toLogback. 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 andlogback). 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 orlog4j.xml in the root of the classpath). So for Maven users this is your dependency declaration:

<dependencies>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.0.0.RELEASE</version>
      <scope>runtime</scope>
   </dependency>
   <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      <scope>runtime</scope>
   </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

2.4 New module organization and build system

The framework modules have been revised and are now managed separately with one source-tree per module jar:

  • org.springframework.aop

  • org.springframework.beans

  • org.springframework.context

  • org.springframework.context.support

  • org.springframework.expression

  • org.springframework.instrument

  • org.springframework.jdbc

  • org.springframework.jms

  • org.springframework.orm

  • org.springframework.oxm

  • org.springframework.test

  • org.springframework.transaction

  • org.springframework.web

  • org.springframework.web.portlet

  • org.springframework.web.servlet

  • org.springframework.web.struts

2.5.3 The Inversion of Control (IoC) container

Java based bean metadata

Some core features from the JavaConfig project have been added to the Spring Framework now. This means that the following annotations are now directly supported:

  • @Configuration

  • @Bean

  • @DependsOn

  • @Primary

  • @Lazy

  • @Import

  • @ImportResource

  • @Value

Here is an example of a Java class providing basic configuration using the new JavaConfig features:

package org.example.config;

@Configuration
public class AppConfig {
    private @Value("#{jdbcProperties.url}") String jdbcUrl;
    private @Value("#{jdbcProperties.username}") String username;
    private @Value("#{jdbcProperties.password}") String password;

    @Bean
    public FooService fooService() {
        return new FooServiceImpl(fooRepository());
    }

    @Bean
    public FooRepository fooRepository() {
        return new HibernateFooRepository(sessionFactory());
    }

    @Bean
    public SessionFactory sessionFactory() {
        // wire up a session factory
        AnnotationSessionFactoryBean asFactoryBean =
            new AnnotationSessionFactoryBean();
        asFactoryBean.setDataSource(dataSource());
        // additional config
        return asFactoryBean.getObject();
    }

    @Bean
    public DataSource dataSource() {
        return new DriverManagerDataSource(jdbcUrl, username, password);
    }
}

To get this to work you need to add the following component scanning entry in your minimal application context XML file.

<context:component-scan base-package="org.example.config"/>
<util:properties id="jdbcProperties" location="classpath:org/example/config/jdbc.properties"/>
        

Or you can bootstrap a @Configuration class directly usingAnnotationConfigApplicationContext:

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    FooService fooService = ctx.getBean(FooService.class);
    fooService.doStuff();
}
See Section 5.12.2, “Instantiating the Spring container using AnnotationConfigApplicationContext for full information on AnnotationConfigApplicationContext.


Defining bean metadata within components

@Bean annotated methods are also supported inside Spring components. They contribute a factory bean definition to the container. SeeDefining bean metadata within components for more information

2.5.4 General purpose type conversion system and field formatting system

A general purpose type conversion system has been introduced. The system is currently used by SpEL for type conversion, and may also be used by a Spring Container and DataBinder when binding bean property values.

In addition, a formatter SPI has been introduced for formatting field values. This SPI provides a simpler and more robust alternative to JavaBean PropertyEditors for use in client environments such as Spring MVC.

2.5.5 The Data Tier

Object to XML mapping functionality (OXM) from the Spring Web Services project has been moved to the core Spring Framework now. The functionality is found in theorg.springframework.oxm package. More information on the use of theOXM module can be found in the Marshalling XML using O/X Mappers chapter.

2.5.6 The Web Tier

The most exciting new feature for the Web Tier is the support for building RESTful web services and web applications. There are also some new annotations that can be used in any web application.

Comprehensive REST support

Server-side support for building RESTful applications has been provided as an extension of the existing annotation driven MVC web framework. Client-side support is provided by theRestTemplate class in the spirit of other template classes such asJdbcTemplate and JmsTemplate. Both server and client side REST functionality make use ofHttpConverters to facilitate the conversion between objects and their representation in HTTP requests and responses.

The MarshallingHttpMessageConverter uses the Object to XML mapping functionality mentioned earlier.

Refer to the sections on MVC and the RestTemplate for more information.

@MVC additions

A mvc namespace has been introduced that greatly simplifies Spring MVC configuration.

Additional annotations such as @CookieValue and@RequestHeaders have been added. See Mapping cookie values with the @CookieValue annotation and Mapping request header attributes with the @RequestHeader annotation for more information.

2.5.7 Declarative model validation

Several validation enhancements, including JSR 303 support that uses Hibernate Validator as the default provider.

2.5.8 Early support for Java EE 6

We provide support for asynchronous method invocations through the use of the new @Async annotation (or EJB 3.1's @Asynchronous annotation).

JSR 303, JSF 2.0, JPA 2.0, etc

2.5.9 Support for embedded databases

Convenient support for embedded Java database engines, including HSQL, H2, and Derby, is now provided.



3. New Features and Enhancements in Spring Framework 3.1

This is a list of new features for Spring Framework 3.1. A number of features do not have dedicated reference documentation but do have complete Javadoc. In such cases, fully-qualified class names are given. See alsoAppendix C, Migrating to Spring Framework 3.1

3.1 Cache Abstraction

3.2 Bean Definition Profiles

  • XML profiles (SpringSource Team Blog)

  • Introducing @Profile (SpringSource Team Blog)

  • See org.springframework.context.annotation.Configuration Javadoc

  • See org.springframework.context.annotation.Profile Javadoc

3.3 Environment Abstraction

3.4 PropertySource Abstraction

  • Unified Property Management (SpringSource Team Blog)

  • See org.springframework.core.env.Environment Javadoc

  • See org.springframework.core.env.PropertySource Javadoc

  • See org.springframework.context.annotation.PropertySource Javadoc

3.5 Code equivalents for Spring's XML namespaces

Code-based equivalents to popular Spring XML namespace elements <context:component-scan/>, <tx:annotation-driven/> and <mvc:annotation-driven> have been developed, most in the form of@Enable annotations. These are designed for use in conjunction with Spring's@Configuration classes, which were introduced in Spring Framework 3.0.

  • See org.springframework.context.annotation.Configuration Javadoc

  • See org.springframework.context.annotation.ComponentScan Javadoc

  • See org.springframework.transaction.annotation.EnableTransactionManagement Javadoc

  • See org.springframework.cache.annotation.EnableCaching Javadoc

  • See org.springframework.web.servlet.config.annotation.EnableWebMvc Javadoc

  • See org.springframework.scheduling.annotation.EnableScheduling Javadoc

  • See org.springframework.scheduling.annotation.EnableAsync Javadoc

  • See org.springframework.context.annotation.EnableAspectJAutoProxy Javadoc

  • See org.springframework.context.annotation.EnableLoadTimeWeaving Javadoc

  • See org.springframework.beans.factory.aspectj.EnableSpringConfigured Javadoc

3.6 Support for Hibernate 4.x

  • See Javadoc for classes within the new org.springframework.orm.hibernate4 package



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值