Spring开发Service层
service层的作用:
- 业务逻辑操作(某些操作依赖于Dao层),将操作后的结果在返回出去给View层根据结果展现视图效果。
在开发完dao层(Spring+MyBatis)后,对Service层进行开发
基本步骤:
- 使用xml文件配置:spring/spring-service.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
>
<!--扫描service包下所有使用注解的类型-->
<context:component-scan base-package="cn.xiaofang.service"></context:component-scan>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置基于注解的声明式事务 默认使用注解来管理事务行为-->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
- 建立用来封装对象的类,实现数据在各个层的传递
- 建立异常类来处理各种异常(如超时异常、重复秒杀异常)
- 建立类来实现业务代码(接口、实现类)
业务层设计技巧
- 业务接口设计和封装
- Spring IOC配置技巧(第三方实例由xml配置(如数据库链接池相关),自己建立的实例由注解配置(dao实例))
- Spring声明事务使用和理解(事务由注解实现:事务长度尽量短、只读操作不需要事务)
细节:
- 使用枚举表示常量数据字段
- 创建异常包(来检测事务是否执行顺利),要使用运行期异常,Spring只有运行期异常才回滚事务
- 在并发量高的系统中事务控制
1.保证事务方法的执行时间尽可能短,不要穿插其他网络操作RPC/HTTP请求或者剥离到事务方法外部
2.不是所有的方法都需要事务,如只有一条修改操作,只读操作不要事务控制
3.使用@Transactional注解事务 - logger来进行测试日志记录
开发后想法:
- 为什么用IOC:
1.对象创建统一托管
2.规范的生命周期管理
3.灵活的依赖注入
4.一致的获取对象(单例)