spring事物零配置方式

首先使用配置文件方式配置数据源:

jdbc.url=jdbc:mysql:///spring
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.username=root

jdbc.password=root

获取数据源:

使用@PropertySource加载配置文件

使用@EnableTransactionManagement开启事物注入

使用@Value读取配置文件

@Bean把dataSource和jdbcTemplate和transactionManager注入到spring容器中

@PropertySource(value="classpath:jdbc.properties")
@EnableTransactionManagement
public class JdbcConfig {

@Value("${jdbc.url}")
private String url;
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;


@Bean(name="dataSource")
public DataSource getDataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}

@Bean(name="jdbcTemplate")
public JdbcTemplate getJdbcTemplate(@Qualifier("dataSource")DataSource dataSource){
JdbcTemplate temp = new JdbcTemplate();
temp.setDataSource(dataSource);
return temp;
}

@Bean(name="transactionManager")
public DataSourceTransactionManager getTransactionManager(@Qualifier("dataSource")DataSource dataSource){
DataSourceTransactionManager tm = new DataSourceTransactionManager();
tm.setDataSource(dataSource);
return tm;

}

}

Configurable标识为一个配置类

ComponentScan扫描包

Import加载数据源配置

@Configurable
@ComponentScan(basePackages="cn.sm1234")
@Import(JdbcConfig.class)
public class SpringConfig {

}

@Repository
public class AccountDaoImpl implements AccountDao {

//注入JdbcTemplate
@Resource(name="jdbcTemplate")
private JdbcTemplate temp;

@Override
public void outMoney(String name, Double money) {
temp.update("update account set money = money - ? where name = ? ",money,name);
}


@Override
public void InMoney(String name, Double money) {
temp.update("update account set money = money + ? where name = ? ",money,name);
}

}

Service标注业务层组件

Transactional基于注解方式事物

@Service
@Transactional(isolation=Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {

@Resource
private AccountDao accountDao;

@Override
public void translate(String outName, String inName, Double money) {
//从账户扣钱
accountDao.outMoney(outName,money);

//int i = 100/0;

//把钱打入账户
accountDao.InMoney(inName, money);
}
}

猜你喜欢

转载自blog.csdn.net/qq_28524127/article/details/80951580