Spring代理事务

  用户通过TransactionProxyFactoryBean代理类对需要管理的业务类进行代理,这种方式不推荐。

Student类

package com.smart.domain;

public class Student {
    private int studentId;
    private String stuName;
    private String sex;
    private int age;
    private String phone;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

StudentDAO

package com.smart.dao;

@Repository
public class StudentDao {
    private JdbcTemplate jdbcTemplate;

    public void addStudent(final Student student){
        final String sql="insert into t_stu(name,sex,age,phone) values(?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,student.getStuName());
                ps.setString(2,student.getSex());
                ps.setInt(3,student.getAge());
                ps.setString(4,student.getPhone());
                return ps;
            }
        },keyHolder);
        student.setStudentId(keyHolder.getKey().intValue());
    }

    public void addSudentAgain(final Student student){
       Object[] params=new Object[]{student.getStuName(),student.getSex(),student.getAge(),student.getPhone()};
        final String sql="insert into t_stu(name,sex,age,phone) values(?,?,?,?)";
        jdbcTemplate.update(sql,params);
    }

    public Student getStudent(final int stuId){
        String sql="select name,sex,age,phone from t_stu where stu_id=?";
        final Student student=new Student();
        jdbcTemplate.query(sql, new Object[]{stuId}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                student.setStudentId(stuId);
                student.setStuName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setPhone(rs.getString("phone"));
            }
        });
        return student;
    }

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

StudentService

package com.smart.service;

@Service
public class StudentService {
    private StudentDao studentDao;

    public void addStudent(Student student){
        studentDao.addStudent(student);
    }

    public void addStudentAgain(Student student){
        studentDao.addSudentAgain(student);
    }

    public Student getStudent(final int stuId){
        Student student = studentDao.getStudent(stuId);
        return student;
    }

    @Autowired
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}

配置文件applicationContext-proxy.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:component-scan base-package="com.smart"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}"/>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
          p:dataSource-ref="dataSource"/>

    <bean id="studentServiceTarget" class="com.smart.service.StudentService"
          p:studentDao-ref="studentDao"/>

    <bean id="studentService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
          p:transactionManager-ref="txManager"
          p:target-ref="studentServiceTarget">
          <property name="transactionAttributes">
              <props>
                  <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                  <prop key="*">PROPAGATION_REQUIRED</prop>
              </props>
          </property>
    </bean>
</beans>

测试类

package com.smart;

@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-proxy.xml"})
public class TestStudentService  extends AbstractTransactionalTestNGSpringContextTests{
    @Autowired
    private StudentService studentService;

    @Test
    public void testAddStudent(){
        Student student = new Student();
        student.setStuName("xiaoxiao");
        student.setSex("男");
        student.setAge(18);
        student.setPhone("186995");
        studentService.addStudent(student);
    }

    @Test
    public void testAddStudentAgain(){
        Student student = new Student();
        student.setStuName("xiaocun");
        student.setSex("女");
        student.setAge(18);
        student.setPhone("186995");
        studentService.addStudentAgain(student);
    }

    @Test
    public void testGetStudent(){
        Student student = studentService.getStudent(27);
        System.out.println(student);
    }
}

拓展:所有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"
    xmlns:context="http://www.springframework.org/schema/context"
    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.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
    </bean>  
 
    <!-- 定义事务管理器(声明式的事务) -->  
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  
            lazy-init="true" abstract="true">  
        <!-- 配置事务管理器 -->  
        <property name="transactionManager" ref="transactionManager" />  
        <!-- 配置事务属性 -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>  
            </props>  
        </property>  
    </bean>    
   
    <!-- 配置DAO -->
    <bean id="userDaoTarget" class="com.bluesky.spring.dao.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <bean id="userDao" parent="transactionBase">  
        <property name="target" ref="userDaoTarget" />   
    </bean>
</beans>

 

posted on 2018-12-02 23:14  溪水静幽  阅读(223)  评论(0)    收藏  举报