spring中的切点(AOP)和事务(ACID)的结合使用 spring.xml的配置



    
    
    
	
	
	
	
	
	
	
	
		
		
		
		
	
	
	
		
		
	
	
	
	
		
		
	
	
	
	
		
			
			
			
			
			
		
	
	
	
	
							
		
		
		
	



例:转钱的案例

package lesson04.testm;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import lesson04.testm.dao.AcDaoImpl;

public class TestTa {
    static AcDaoImpl d;
    static Connection conn;
    static{
        ApplicationContext context=new ClassPathXmlApplicationContext("lesson04/testm/spring.xml");
        d=(AcDaoImpl)context.getBean("acDaoImpl");
    }
    public static void main(String[] args) throws Exception {
       //当执行此方法会开启一个事务
    	d.UpdateAminus(10);
    }
}




package lesson04.testm.dao;

import java.io.FileNotFoundException;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;


@Repository
public class AcDaoImpl {
    @Autowired
    JdbcTemplate jdbc;
    @Autowired
    BcDaoImpl b;
    //这两个动作处在同一个方法中     默认就会处在同一事务中
    public void UpdateAminus(int money) throws Exception{
        //执行减钱动作
    	String sql="update mymoney set lostedmoney=lostedmoney-"+money+" where id=1";
        jdbc.execute(sql);
        //执行加钱动作
        b.saveBadd(money);
        throw new FileNotFoundException();
        
    }
}



package lesson04.testm.dao;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BcDaoImpl {
    @Autowired
    JdbcTemplate jdbc;
   
    
    //执行加钱的动作
    public void saveBadd(int money) throws SQLException{
        String sql="update mymoney set lostedmoney=lostedmoney+"+money+" where id=2";
        jdbc.execute(sql);
    }
}




你可能感兴趣的:(spring)