文章目录
#Spring使用
前言
要使用Spring来进行CRUD操作,增删改一定需要**事务管理器**来手动提交事务和回滚事务。查询不需要事务管理器。
在处理预装sql语句中,预处理对象需要多例。例如PreparedStatement、
QueryRunner( org.apache.commons.dbutils)都在注入依赖的时候需要添加scope=“prototype”,是因为单程线程不安全,在增删改的时候。
1、通用步骤
###0、pom.xml配置依赖坐标
1、三层架构模式
1、创建实体类(domain包下)
- 实体类的属性名要与sql的列名相同
- 生成Setter和Getter方法
2、创建持久层接口及实现类(dao和impl包下)
- 具体执行sql语句的方法
3、创建业务层接口类及实现类(service的impl包和service包下)
- 设置成员变量为持久层对象
- 为引用的对象设置Setter方法
private IAccountDao accountDao;
- 创建执行方法及内容
2、测试(spring整合junit测试)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class JdbcTemplateTest {
@Autowired
private IAccountService as;
@Test
public void Test(){
as.transfer("aaa", "bbb", 100f);
}
}
2、xml配置使用
1、创建配置文件bean.xml
1、引入相关的头部信息及模板
-
普通的bean标签信息
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 将bean加入到Spring容器 --> <bean id="..." class="..."> <!-- 此bean的协作者和配置 --> </bean> <!-- more bean definitions go here --> </beans>
-
AOP头信息
<?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 一个HTTP会话作用域的bean,公开为代理 --> <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> <!-- 指示容器代理周围的bean --> <aop:scoped-proxy/> </bean> <!-- 注入了上述bean的代理的单一作用域bean --> <bean id="userService" class="com.foo.SimpleUserService"> <!-- 对 bean的引用 --> <property name="userPreferences" ref="userPreferences"/> </bean> </beans>
-
事务管理器头信息
<?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" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 这个需要注入spring容器的对象 --> <bean id="fooService" class="x.y.service.DefaultFooService"/> <!-- 配置事务管理器,用处在<aop:advisor/> --> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- 事务语法 --> <tx:attributes> <!-- 所有的get方法都是制度--> <tx:method name="get*" read-only="true"/> <!-- 其他的方法使用默认设置,参考下方 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 确保在执行Service接口定义的任何操作时运行上述事务建议 --> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.Service.impl*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/> <property name="username" value="scott"/> <property name="password" value="tiger"/> </bean> <!-- 同样,配置事务管理器的数据源 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- other <bean/> definitions here --> </beans>
-
注解头部信息 若是有aop,则复制有aop那一行,将aop改为context即可
<?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"
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">
<context:annotation-config/>
</beans>
2、注入相关的依赖
1、dao(持久层)引用的对象(成员变量有必须有Setter方法)和dao
<!--配置dataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置账户的持久层-->
<bean id="accountDao" class="com.dao.impl.accountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
2、注入service(业务层)的依赖
<!--配置service-->
<bean id="accountService" class="com.service.Impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
3、注入业务层引用的对象(成员变量)依赖
<!--配置事务管理器-->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManger">
<tx:attributes>
<!--配置事务属性
isolation:指定事务的隔离级别。默认值是default,表示使用数据库的隔离剂级别
propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择,查询的方法可以选择SUPPORTS
read-only:用于指定事务是否为只读,只有查询方法才能设置为true。默认值为false,表示读写
timeout:用于指定事务的超时时间,默认值为-1,表示永不超时。如果指定了数值,以秒为单位
rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,表示任何异常都回滚。
-->
<tx:method name="transfer" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"></tx:method>
</tx:attributes>
</tx:advice>
3.1、或者配置切面(事务通知)
<!--配置Aop-->
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.service.Impl.*.*(..))"/>
<aop:aspect id="txAdvice" ref="transManger">
<aop:before method="beginTransaction" pointcut-ref="pt"/>
<aop:after-returning method="commit" pointcut-ref="pt"/>
<aop:after-throwing method="rollback" pointcut-ref="pt"/>
<aop:after method="release" pointcut-ref="pt"/>
</aop:aspect>
</aop:config>
3、XML+注解配置
1、注入相关依赖(类、成员变量)
2、配置bean
1、扫描包
<!--配置容器时要扫描包-->
<context:component-scan base-package="com"></context:component-scan>
2、配置jar
<!--配置JDBCTemplate-->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置dataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--
spring基于注解的声明式事务控制配置步骤
1、配置事务管理器
2、开启spring对注解事务的支持
3、在需要事务支持的地方使用注解@Transactional
-->
<!--配置事务管理器-->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
3、开启spring对注解AOP/事务的支持
<!-- 启用spring对AspectJ注解的支持 -->
<aop:aspectj-autoproxy/>
<!-- 开启spring对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManger"/>
4、纯注解
1、创建一个配置包(config)
1、创建一个主配置类(springConfiguration)
/**
*spring配置类,相当于bean.xml
**/
@Configuration//标记为主配置
@ComponentScan("com")//扫描包
@Import({jdbcConfig.class, transactionConfig.class})//引入配置类
@PropertySource("classpath:jdbcConfig.properties")//配置文件源
@EnableTransactionManagement//开启事务支持
public class SpringConfiguration {
}
2、创建一个配置文件,用来连接数据库(jdbcConfig.properties)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring
jdbc.username=root
jdbc.password=123456
4、创建一个连接数据库的类(jdbcConfig)
public class jdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
@Bean(name = "dataSource")
public DataSource createDataSource() {
System.out.println(driver+url+username+password);
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
5、 和事务相关的配置类(或者是其他)
public class transactionConfig {
/**
* 用于创建事务管理对象
* @param ds
* @return
*/
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource ds){
return new DataSourceTransactionManager(ds);
}
}
2、将类加入spring容器,并且注入相关的依赖
@Repository("accountDao")//加入spring容器
public class accountDaoImpl implements IAccountDao {
@Autowired//注入依赖
private JdbcTemplate jt;
@Service("accountService")
@Transactional(readOnly = true, propagation= Propagation.SUPPORTS)//定义事务类
public class AccountService implements IAccountService {
@Autowired
private IAccountDao accountDao;
,并且注入相关的依赖
@Repository("accountDao")//加入spring容器
public class accountDaoImpl implements IAccountDao {
@Autowired//注入依赖
private JdbcTemplate jt;
@Service("accountService")
@Transactional(readOnly = true, propagation= Propagation.SUPPORTS)//定义事务类
public class AccountService implements IAccountService {
@Autowired
private IAccountDao accountDao;