代码示例
package com.lmgd.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration // 配置类
@ComponentScan(basePackages = "com.lmgd") // 组件扫描(扫描哪些包下的组件)
@EnableTransactionManagement //开启事务 (事务使用:在 serverImpl 类上加上 @Transactional 注解即可,不用配置切入点、切面等等)
public class MyConfig {
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://test");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入 dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
测试
1、测试发生异常是否回滚事务、没有发生异常是否会正常提交事务
2、是否可以正常获得bean对象、扫描到包下的组件、连接数据库等等
public class Test {
@org.junit.Test
public void testAccount() {
//ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
UserServer userServer = context.getBean("userServer", UserServer.class);
userServer.account();
}
}


