在Spring 2.5及以后的版本中,提供了注释和命名空间来简化Spring的配置。下面是一些常用配置分享。


1、@Autowired注释

  以前给一个Bean配置属性时,Bean必须配置<property name="propName" ref="beanId"/>,然后在Java文件,还必须增加属性propname的getter和setter方法。
有了@Autowired注释后,我们可以简化配置文件和getters和setters方法。
- 1)注释属性

@Autowired
private BeanClassName propName;

  当然,我们还必须告诉Spring容器,当它启动时,就去扫描所有的Bean,然后自动注入。

<!-- 对具有@Autowired注释的Bean进行注入 -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

我们也可以注释构造函数和方法。

  • 2)注释构造函数
@Autowired
public MainBean(PropBeanA propBeanA, PropBeanB propBeanB){
this.propBeanA = propBeanA;
this.PropBeanB = PropBeanB ;
}
  • 3)注释方法
@Autowired
public void setPropBean(PropBean propBean) {
this.propBean = propBean;
}
  • 4)@Autowired的相关属性

  在默认情况下使用@Autowired注释进行自动注入时,Spring容器中匹配的候选Bean数目必须有且仅有一个。当Springp容器找不到一个匹配的Bean时(可能是没有配置该Bean或是Bean的属性名写错了),Spring容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的Bean。

  • (1)当Bean是可选的,或是不能确定Bean一定有,可以用@Autowired(required = false),这样在找不到匹配Bean 时也不报错,该属性默认为true。
  • (2)与上面的相反,当Bean有多个时,我们可以通过@Qualifier(“beanId”)还唯一确定一个所引用的Bean,与@Autowired配合使用,它也有三种使用的地方。

2、@Component注释

  虽然我们可以通过@Autowired在Bean类中使用自动注入功能,但是Bean还是在XML文件中通过进行定义的,通过@Component注释可以实现无需在配置文件中配置Bean的目的。

import org.springframework.stereotype.Component;
@Component
public class BeanClassNameA {
// ......
}
使用@Autowired
@Component
public class BeanClassNameB {
@Autowired
private BeanClassNameA propBeanA; // ......
}

  因为没有配置,我们必须告诉Spring容器启用类扫描机制并自动注入了:

前面的AutowiredAnnotationBeanPostProcessor可以去掉了,这行的作用后面介绍。
- 1)@Component有个可选参数,指定Bean的名称@Component(“beanId”)
- 2)与@Component配合使用,可以通过@Scope指定Bean的作用范围,比如:@Scope(“prototype”)

3、其他注释

  Spring除了提供@Component注释外,还定义了几个注释:@Repository、@Service 和 @Controller。
在目前的Spring 2.5中,这3个注释和@Component是等效的,但是从注释类的命名上,很容易看出这3个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这3个注释和@Component相比没有什么新意,但Spring将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用@Repository、@Service和 @Controller对分层中的类进行注释,而用@Component对那些比较中立的类进行注释。

4、<context:annotation-config />

将隐式地向Spring容器注册 AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor这4个BeanPostProcessor。

5、<context:component-scan base-package="......" />

通过,Spring会递归扫描类注释。
具体的说明可以参考:http://springindepth.com/book/annotation-based-bean-config-ioc-container-configuration.html

6、JavaEE应用@Controller

在使用SpringMVC中,可以通过@Controller简化配置

@Controller
@RequestMapping("/welcome.htm")
public class SomeNameController {
@RequestMapping(method = RequestMethod.GET)
public void doGet(ModelMap model, WebRequest request) {
// ...
}
}

关于@Controller,在以后的文章中介绍,敬请关注。

7、简化配置文件

对于属性,我们一般都是通过以下配置的:

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
简化之后为:
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />

使用方法介绍,我相信就没必要了,注意这两种方式可以一起使用的。

8、命名空间

  在以上的

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:osgi="http://www.springframework.org/schema/osgi" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName">

XSD文件版本小技巧:不要增加版本(如直接使用spring-context.xsd),当然要加也是spring-context-2.5.xsd

由于介绍内容比较多,感觉都比较空,还有一些没有介绍具体:
- (1)JavaEE的注释,主要是@Controller;
- (2)JPA注释,@Entity,@Table;
- (3)JSR-250的注释,@Resource、@PostConstruct、@PreDestroy等。

下面贴出我的Spring配置文件的内容。

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:osgi="http://www.springframework.org/schema/osgi" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName"> <!-- Activates annotation-based bean configuration -->
<context:component-scan base-package="com.alipay.common" /> <!-- DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/work_shop?useUnicode=true&amp;characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="manager" />
</bean> <!-- SqlMapClient -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocations">
<list>
<value>classpath:sqlmap/sqlmap-config.xml</value>
</list>
</property>
</bean> <!-- SqlMapClientDAO -->
<bean id="sqlMapClientDAO" abstract="true" p:dataSource-ref="dataSource"
p:sqlMapClient-ref="sqlMapClient" /> <!-- TransactionTemplate -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" /> <!-- TransactionManager -->
<bean id="mockTransactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate"
p:transactionManager-ref="transactionManager" /> <!-- DAO -->
<bean id="siteUserDAO" class="com.alipay.dal.ibatis.IbatisSiteUserDAO"
parent="sqlMapClientDAO" />
<!-- END OF DAO --> <!-- MANAGER -->
<bean id="siteUserManager" class="com.alipay.biz.manager.impl.SiteUserManagerImpl" />
<!-- END OF MANAGER -->
<!-- FACADE-->
<!-- END OF FACADE-->
<!-- OSGI SERVICE-->
<!-- END OF OSGI SERVICE-->
</beans>

Spring注释与简化配置的更多相关文章

  1. 7 -- Spring的基本用法 -- 11... 基于XML Schema的简化配置方式

    7.11 基于XML Schema的简化配置方式 Spring允许使用基于XML Schema的配置方式来简化Spring配置文件. 7.11.1 使用p:命名空间简化配置 p:命名空间不需要特定的S ...

  2. Spring事务支持:利用继承简化配置

    因为事务代理的实现类是 TransactionProxyFactoryBean . 事务代理Bean必须注入事务管理器. 大部分情况下,每个事务代理的事务属性大同小异,对于这种情况,Spring提供了 ...

  3. 【Java】Spring之基于注释的容器配置(四)

    注释是否比配置Spring的XML更好? 基于注释的配置的引入引发了这种方法是否比XML“更好”的问题.答案是每种方法都有其优点和缺点,通常,由开发人员决定哪种策略更适合他们.由于它们的定义方式,注释 ...

  4. Spring注释(转)

    转自:http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/#ibm-pcon 概述 注释配置相对于 XML 配置具有很多的优势: 它 ...

  5. CAS Spring Security 3 整合配置(转)

    一般来说, Web 应用的安全性包括用户认证( Authentication )和用户授权( Authorization )两个部分.用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否 ...

  6. Spring Boot 2.0 配置图文教程

    摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 本章内容 自定义属性快速入门 外化配置 自动配置 自定义创建 ...

  7. spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

  8. Spring Cloud Feign 自定义配置(重试、拦截与错误码处理) 实践

    Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 目录 Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 引子 FeignClient的 ...

  9. Spring Boot的自动配置原理及启动流程源码分析

    概述 Spring Boot 应用目前应该是 Java 中用得最多的框架了吧.其中 Spring Boot 最具特点之一就是自动配置,基于Spring Boot 的自动配置,我们可以很快集成某个模块, ...

随机推荐

  1. FZU 2151 OOXX Game

    OOXX Game Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit St ...

  2. 【转载】Ogre的内存分配策略

    原文:Ogre的内存分配策略 读这个之前,强烈建议看一下Alexandrescu的modern c++的第一章关于policy技术的解释.应该是这哥们发明的,这里只是使用. 首先列出涉及到的头文件:( ...

  3. jquery相对选择器,又叫context选择器,上下文选择器;find()与children()区别

    jquery相对选择器有两个参数,jQuery函数的第二个参数可以指定DOM元素的搜索范围(即以第二个参数指定的内容为容器查找指定元素). 第二个参数的不同的类型,对应的用法如下表所示. 类型 用法 ...

  4. Lambda表达式之Python

    一.lambda函数 1.lambda函数基础: lambda函数也叫匿名函数,即,函数没有具体的名称,而用def创建的方法是有名称的.如下: """命名的foo函数&q ...

  5. 使用httpclient时候,出现“Too many open files”问题

    最近接触的sendHttpPostRequest的问题比较多,近期碰到了关于 "java.net.SocketException: Too many open files" 的问题 ...

  6. poj 2985 The k-th Largest Group 树状数组求第K大

    The k-th Largest Group Time Limit: 2000MS   Memory Limit: 131072K Total Submissions: 8353   Accepted ...

  7. XAF应用开发教程(六)控制器

    是的,XAF也是MVC结构的,但不仅限于MVC,ViewModel也存在,它是一项复合技术,AOP,ORM,MVC都有. 真实运行的系统中,仅有增删改查功能肯定是远远不够的,ERP.CRM等系统的开发 ...

  8. 花神的数论题(数位dp)

    规定sum[i] 为i里面含1的个数 ,求从1-N sum[i]的乘积. 数为64位内的,也就是sum[i]<=64的,这样可以dp求出1-N中含k个1的数有多少个,快速幂一下就可以了. 有个地 ...

  9. xutils使用过程

    1,导入xutils的jar包 2,添加xutils需要使用的权限 <uses-permission android:name="android.permission.INTERNET ...

  10. 转:C/C++基本数据类型所占字节数

    参考:http://blog.csdn.net/vast_sea/article/details/8076934 关于这个基本的问题,很早以前就很清楚了,C标准中并没有具体给出规定那个基本类型应该是多 ...