spring复习:(42)配置文件的方式实现事务(TransactionProxyFactoryBean)

一、定义服务接口:

package cn.edu.tju.study.service.transaction2;

public interface StudentService {
    public void addStudent(String name, int age);
}

二、定义服务实现类

package cn.edu.tju.study.service.transaction2;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService{
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

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

    @Override
    public void addStudent(String name,int age) {
        String sql = "insert into student values('";
        sql += name;
        sql +="'";
        sql += ",";
        sql += age;
        sql += ")";
        jdbcTemplate.execute(sql);
        int i = 1/0;
        jdbcTemplate.execute(sql);

    }
}

三、配置文件:





    
        
        
        
        

    
    
        
    



    
        
    

    
        
    


    
        
        
        
            
                PROPAGATION_REQUIRED
            
        
    



四、主类,调用TransactionProxyFactoryBean

package cn.edu.tju.study.service.transaction2;

import cn.edu.tju.study.service.MyConfig3;
import cn.edu.tju.study.service.aspect.MyDemoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TransactionTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("transaction.xml");

        StudentService studentService = context.getBean("myFactoryBean", StudentService.class);

        studentService.addStudent("paul",23);
    }
}

你可能感兴趣的:(Spring,spring,java,后端)