`

谈谈Spring 2.x中简化配置的问题

阅读更多
谈谈Spring 2.x中简化配置的问题

Spring 2.x在配置文件的简化的方面做了很多工作,原来1.x中比较麻烦的配置都已经拥有了比较完美的解决方案。

一、关于集合的配置
1.List
>1.x版本的
<bean id="parentBoss" abstract="true"class="com.baobaotao.attr.Boss"> <--父<bean>
	<property name="favorites">
		<set>
			<value>看报</value>
			<value>赛车</value>
			<value>高尔夫</value>
		</set>
	</property>
</bean>


>2.x版本的
<util:list id="favoriteList1" list-class="java.util.LinkedList">
	<value>看报</value>
	<value>赛车</value>
	<value>高尔夫</value>
</util:list>


2.Set
> 1.x
<bean id="boss1" class="com.baobaotao.attr.Boss">
	<property name="favorites">
	   <set> 
	      <value>看报</value>
	      <value>赛车</value>
	      <value>高尔夫</value>
	   </set>
	</property>
</bean>

> 2.x
    
   <util:set id="favoriteSet1">
	   <value>看报</value>
	   <value>赛车</value>
	    <value>高尔夫</value>
   </util:set>

   3.Map
> 1.x
<bean id="boss1" class="com.baobaotao.attr.Boss">
    <property name="jobs">
	<map>
	      <!--Map第一个元素-->
               <entry> 
	          <key><value>AM</value></key>
	          <value>会见客户</value>
	       </entry>
	      <!--Map第二个元素-->
               <entry> 
	          <key><value>PM</value></key>
	          <value>公司内部会议</value>
	      </entry>		      
	</map>
    </property>
</bean>

> 2.x
<util:map id="emails1">
	<entry key="AM" value="会见客户" />
	<entry key="PM" value="公司内部会议" />
</util:map>


   4. Properties

> 1.x
<bean id="boss1" class="com.baobaotao.attr.Boss">
	<property name="mails">
	    <props>
	       <prop key="jobMail">john-office@baobaotao.com</prop>
	       <prop key="lifeMail">john-life@baobaotao.com</prop>
	    </props>
	</property>
</bean>


> 2.x
  <util:properties id="emailProps1" location="classpath:com/baobaotao/fb/mails.properties"/>

可以在一个属性文件中直接配置属性,这比较符合一般的项目习惯。

二、 关于事务配置


1.1.x
  <bean id="bbtForum" 
	class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
	<property name="transactionManager" ref="txManager" /> 
	<property name="target" ref="bbtForumTarget"/>
	<property name="transactionAttributes"> 
		<props>
			<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> 
			<prop key="*">PROPAGATION_REQUIRED</prop> 
		</props>
	</property>
  </bean>


2.2.x

有两种新方法
a)使用@Transactional注解
在需要的服务类或服务方法处直接打上@Transactional注解,然后在Spring配置文件中启用注解事务驱动就可以了:

@Transactional 
public class BbtForumImpl implements BbtForum {
	@Transactional(readOnly=true) 
	public Forum getForum(int forumId) {
		return forumDao.getForum(forumId);
	}
       。。。。
}

在Spring配置文件中相应添加上:
<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>

这样就OK了,简单吧:)

b)使用aop/tx

如果你的Service服务类都很规范,我觉得使用aop/tx更方面,因为不用到处打注解,在一处集中配置就OK了,可谓运筹帷幄之中,决胜于千里之外:)
 
     <aop:config> 
	  <aop:pointcut id="serviceMethod" 
		      expression="execution(* com.baobaotao.service.*Forum.*(..))" />
	  <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" /> 
      </aop:config>
     <tx:advice id="txAdvice" transaction-manager="txManager"> 
        <tx:attributes> 
            <tx:method name="get*" read-only="false"/>
            <tx:method name="add*" rollback-for="Exception" />
            <tx:method name="update*"/>         
        </tx:attributes>
    </tx:advice>
  


三、关于AOP配置

  原来1.x的AOP太麻烦了,提都不想提,直接说一下2.x的AOP。
Spring 2.x使用@AspectJ来描述切面,由于@AspectJ的语法描述能力超强,因此在Spring 2.x中使用AOP真的非常方便。

    在使用@AspectJ之前,首先你得保证你所使用的JDK的版本是5.0及以上版本,否则无法使用注解技术。
Spring在处理@Aspect注解表达式时,需要使用位于spring/lib/asm下asm关联类库,将该类库的三个类包加入到类路径中:asm-2.2.2.jar、asm-commons-2.2.2.jar和asm-util-2.2.2.jar。我们在第一章中了解了asm类库的用途,它是轻量级的字节码处理框架,因为Java的反射机制无法获取入参名,Spring就利用asm处理@AspectJ中所描述的方法入参名。

    此外,Spring采用AspectJ提供的@AspectJ注解类库及相应的解析类库,它位于spring/lib/aspectj目录下,将目录下的aspectjrt.jar和aspectjweaver.jar类包加入类路径中。
在做好上节中所提到的前置工作后,我们就可以开始编写一个基于@AspectJ的切面了,首先来看一个简单的例子,以便对@AspectJ有一个切身的认识。

   @AspectJ采用不同的方式对AOP进行描述, 我们使用NaiveWaiter的例子来说明,这是一个希望引入切面的目标类:
package com.baobaotao;
public class NaiveWaiter implements Waiter {
	public void greetTo(String clientName) {
		System.out.println("NaiveWaiter:greet to "+clientName+"...");
	}
	public void serveTo(String clientName){
		System.out.println("NaiveWaiter:serving "+clientName+"...");
	}	
}


下面使用@AspectJ来定义一下切面:
package com.baobaotao.aspectj.aspectj;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//通过该注解将PreGreetingAspect标识为一个切面
@Aspect 
public class PreGreetingAspect{
	@Before("execution(* greetTo(..))") //<---定义切点和增强类型
	public void beforeGreeting(){ //<----增强的横切逻辑
		System.out.println("How are you");
	}
}


然后启动@AspectJ的注解切面驱动就可以了!
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
	<!--基于@AspectJ切面的驱动器-->
        <aop:aspectj-autoproxy /> 
	<bean id="waiter" class="com.baobaotao.NaiveWaiter" />
	<bean class="com.baobaotao.aspectj.example.PreGreetingAspect" />
</beans>


四、关于Spring 2.1添加的新功能

1.原来引入一个外面属性配置文件需要使用以下的方式:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
	   <list>
           <!--指定属性文件地址,可以在这里定义多个属性文件-->
		  <value>classpath:com/baobaotao/place/car.properties</value> 
	   </list>
	</property>
    <property name="fileEncoding" value="utf-8"/>
</bean>

<!--引用外部属性的值,对car属性进行配置-->
<bean id="car" class="com.baobaotao.place.Car">
	<property name="brand" value="${brand}" />
	<property name="maxSpeed" value="${maxSpeed}" />
	<property name="price" value="${price}" />
</bean>


使用Spring 2.1后,你只需要象下面这样配置就可以了:
<context:property-placeholder location=" classpath:com/baobaotao/place/car.properties "/>


3.注解驱动的Bean注入

大家看看这段E文就OK了,
<context:component-scan>: scans classpath using one or more "include"/"exclude" filters, and automatically registers beans
In essence, this is a third way to define beans (1: classic xml, 2:javaconfig (code), 3:<context:component-scan>, matching on annotations or types)
Default naming strategy is based on short classname of discovered bean
@Component and @Repository annotations, when used, can optionally specify a bean name to use
For filter type "annotation", the value of "expression" attribute should resolve to a Java annotation type
For filter type "assignable", the value of "expression" attribute should resolve to a Java type
For filter type "aspectj", the value of "expression" should be an "type expression" (in Pointcut language, perhaps it could be injected?)
Relevant documentation can be found in preliminary spring 2.1 manual, sections 3.10 and 3.11
In addition, this last JIRA comment for http://www.jetbrains.net/jira/browse/IDEADEV-16886#action_163502 contains two links to articles showing example usage of <context:component-scan>
<context:annotation-config> (described in 3.10 in spring 2.1 manual linked above): allows autowiring to be defined using @Resource or @Autowired annotations.


五、关于Spring 2.5添加的新功能
  Spring 2.5继续对context命名空间进行了扩充,添加了好用而强大的context:load-time-weaver,可以让我们更方便地应用AspectJ。大家可以看TSS上的这篇文章,它全面讲解了Spring 2.5的新特性。
http://www.theserverside.com/tt/articles/article.tss?l=IntrotoSpring25

注:以上大部分代码来直接引用自 《精通Spring 2.x--企业应用开发精解》

分享到:
评论
2 楼 笨鸟先飞 2008-03-20  
总结的不错
1 楼 quickselect 2007-12-17  
Spring 2.x比Spring 1.x在配置上确实有很大的简化,不错,总结得很好,收藏了。

相关推荐

    Spring 3.x 中文开发手册.pdf

    Spring 3.x 还引入了属性抽象层,这使得开发者可以在配置文件中使用占位符(placeholder),从而减少因环境变化而频繁更改配置文件的需求。例如,可以使用 `${JAVA_HOME}/com/bank/service/${env}-config.xml"/&gt;` 来...

    spring3.x注解

    Spring 3.x 框架引入了依赖注入的注解,改变了传统的 XML 配置方式,提供了一种更加灵活和方便的依赖配置方式。下面对 Spring 3.x 的注解应用进行详细的介绍。 一、属性装配 在 Spring 3.x 中,提供了两种用于...

    spring4.x.x中文文档

    安全性方面,Spring Security 4.x.x与Spring 4.x.x紧密集成,提供了全面的身份验证和授权功能,包括OAuth2支持,保护了Web应用和RESTful API的安全。 总的来说,Spring 4.x.x中文文档将涵盖这些关键领域的详细内容...

    Spring1.x 和Spring2.x 版本上使用有什么区别

    在Spring1.x中,依赖注入的概念已经引入,但支持的方式相对有限,主要是基于XML配置文件。而Spring2.x在依赖注入方面进行了扩展,增加了基于注解的依赖注入(@Autowired、@Qualifier等),使得代码更加简洁,降低了...

    精通Spring4.x+企业应用开发实战 配套光盘(源码+资源)

    2. **AOP(面向切面编程)**:Spring4.x提供了一种实现AOP的方式,允许开发者定义“切面”来封装系统中横切关注点,如日志、事务管理等,提高代码复用性和可维护性。 3. **Bean管理**:Spring管理Bean的生命周期和...

    spring4.x中的jar包下载,spring4.0.6下载,spring最新稳定版jar包下载

    spring4.x中的jar包下载,spring4.0.6下载,spring最新稳定版jar包下载 http://maven.springframework.org/release/org/springframework/spring/ 这个链接中有各种稳定版的jar包下载 目前官网上大部分都要maven下载

    Spring4.X+Quartz2.X

    在标题"Spring4.X+Quartz2.X"中,我们关注的是如何将这两个框架集成到一个项目中,实现基于Spring的定时任务管理。Spring4.X版本引入了一些新特性,比如对Java 8的全面支持、WebSocket支持以及对RESTful服务的改进,...

    Spring4.X教学视频

    6. **Spring Boot**:虽然不是Spring4.X的直接部分,但Spring Boot是构建现代Spring应用的流行工具,它简化了配置并提供了内置的服务器和starter依赖。视频可能也会涉及Spring Boot的使用。 7. **Spring Security**...

    Spring+3.x企业应用开发实战光盘源码,保证可用

    2. **MVC(模型-视图-控制器)**:Spring 3.x的Web MVC框架提供了更强大的视图解析和数据绑定能力,以及更灵活的配置方式,如基于注解的Controller和HandlerMapping。 3. **JSR-303/JSR-349(Bean验证)**:Spring ...

    《Spring 3.x 企业应用开发实战》lib包

    《Spring 3.x 企业应用开发实战》lib包是一个针对Spring框架3.x版本的实践教程配套资源,其中包含了在实际项目开发中可能用到的各种库文件。这些库文件是Spring框架与其他外部组件交互的关键,它们可以帮助开发者...

    精通Spring4.x企业应用开发实战pdf+源码

    《精通Spring4.x企业应用开发实战》是一本深入解析Spring框架在企业级应用中的实践指南。这本书涵盖了Spring框架的核心概念、重要特性和实际应用,旨在帮助开发者熟练掌握Spring4.x版本的各种开发技能,以提高软件...

    spring 2.x一些东西

    在Spring 2.x中,开发者通过XML配置文件或注解来声明组件及其依赖,容器负责实例化、装配以及管理这些对象。 2. **依赖注入**: 依赖注入是IoC的一种实现方式,它使得对象之间的依赖关系在编译时并不确定,而是在...

    精通spring2.x企业应用开发详解

    《精通Spring 2.x企业应用开发详解》是针对Spring框架2.x版本的一本深度学习教程,旨在帮助读者全面掌握Spring在企业级应用开发中的实践技巧和核心概念。这本书的源代码部分包括了"part5",暗示着它可能涵盖了整个...

    Spring 3.x企业应用开发实战.rar

    2. **数据访问集成**:Spring 3.x增强了对各种数据库访问技术的支持,包括JDBC、Hibernate、MyBatis等,提供了统一的数据访问抽象,简化了数据层的开发。 3. **RESTful支持**:Spring 3.x开始支持RESTful Web服务,...

    Spring4.x官方中文文档

    《Spring4.x官方中文文档》全面解析 Spring框架是Java开发中最广泛使用...通过学习这份文档,开发者不仅可以掌握Spring4.x的核心功能,还能了解到如何利用Spring生态解决实际开发中的问题,提升项目开发的效率和质量。

    Spring3.X企业应用开发实战pdf扫描版+源码光盘

    《Spring3.X企业应用开发实战》是一本深入探讨Spring框架在企业级应用中的实践方法的书籍,PDF扫描版提供了一种方便的电子阅读方式,同时附带的源码光盘则让读者能够动手实践书中所讲解的技术。这本书的核心是帮助...

    精通Spring 4.x 企业应用开发实战 + 源码

    《精通Spring 4.x 企业应用开发实战》是一本深入探讨Spring框架在企业级应用中的实践与源码解析的书籍。Spring作为Java领域最流行的开源框架之一,它为开发者提供了全面的解决方案,包括依赖注入、面向切面编程、...

    精通Spring 4.x 企业应用开发实战.pdf 和项目代码

    在Spring 4.x中,依赖注入是其核心设计原则之一,它允许开发者解耦组件间的依赖关系,提高代码的可测试性和可维护性。通过XML配置、注解或Java配置,我们可以轻松地管理对象的生命周期和依赖关系。 面向切面编程是...

    《Spring 3.x企业应用开发实战》PDF

    9. **Spring Boot**:虽然不是Spring 3.x的一部分,但值得一提的是,Spring Boot是后来推出的一个项目,它简化了Spring应用的初始设置和配置,快速启动和运行。 10. **测试支持**:Spring提供了强大的测试框架,...

    Spring3.x企业应用开发实战(包括源码)绝对完整版

    Spring3.x企业应用开发实战(包括源码)绝对完整版 因未见太大,分8个小块(其他部分在本人资料里面查找),只有前4个每个收1分,后面4个免费下载,共4分,绝对完整,包含所有章节,不完整浏览分享

Global site tag (gtag.js) - Google Analytics