`
zy77612
  • 浏览: 278747 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Spring整理的资料

阅读更多

1. IOC Annotations

1.1 零配置使用场合

   IOC  Annotations 可以实现零配置,但也因为不用在applicationContext.xml中定义了,也就缺乏了灵活的,不修改代码的IOC手段,也无法做一些属性值的配置。

   所以,IOC annotation 常用于Service,Dao,Controller 这些依赖关系比较固定,约定俗成大于配置的地方。

   而XML 配置文件则用于如Database/SessionFactory,Spring  Security这些需要配置的地方。

1.2 ApplicationContext.xml 定义

定义自动扫描Classpath路径,扫描带有@Component/@Service/@Repository的pojo加入applicationContext,并根据@Autowired/@Qualifier  与 @Resource进行IOC配置,并对@PostConstruct 和 @PreDestroy和@Requried进行处理

<context:component-scan base-package="org.springside.examples.miniweb" />

   以下配置除不会扫描@Component/@Service/@Repository外,其他作用同上

 <context:annotation-config />

1.2 @Component/@Service 和 @Repository

    Spring扫描指定的classpath时,会含以上Annotation的类将加其加入ApplicaitonContext中。

    一般@Repository用于DAO层, 而@Service层用于Service层,@Component用于其他,三者在Spring当前版本并没有本质区别,建议只使用@Component。

1.3 @Autowired/@Qualifier  与 @Resource

  @Autowried 与 @Resource都比较灵活,不只能声明于setter函数,还能声明于不按setter规则命名的函数上,以及私有属性上(不建议使用,因为在单元测试时需要以反射注入)

  @Autowried 默认byType,如果需要byName,在变量上增加@Qualifier,另外@Autoried默认隐含了@Required,保证变量一定被注入,如果不需要,用@Autowired(required=false)取消。

  @Resource 默认byName,如果name找不到就会byType, 另可以用name与type属性设定。

1.4 @Requried

    对于非@autowired标注的属性,声明@Required表明明属性必须被注入。

1.5 生命周期Annotation

  • JSR250的@PostConstruct 和 @PreDestroy,比以往的实现接口或者在applicationContext.xml中配置init-method的方式更为方便和标准。
  • {{@PostContruct在所有注入函数执行完毕后执行,而@PreDestroy则在JVM退出的ShutdonwHook中拦截,注意,ShutdownHook对kill -9这种暴烈的关闭无效。
    }}  

2.事务

    因为不喜欢在配置文件里用AspectJ定义事务,宁愿使用Spring的@Transactional annotation在service层上进行标注。

    对于只读的方法,可以加入@Transactional (readOnly=true) 标注以提高性能。

    因为Spring默认只对RuntimeException进行rollback,所以:

    1.所有在service层方法中用throws定义的checkedException,都必须在@Transactional中定义rollbackclass。

    2.所有在service层方法中catch处理了的Exception,又希望Spring辅助rollback的话,必须重抛一个RunTimeException,SpringSide里预定义了一个统一的ServiceException。

   可特别配置事务类型,见

   JavaEE事务资料 六种事务模型与四种事务隔离级别介绍。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics