java1.5 版本之后开始支持注解, spring*2 开始提供注解配置方式, 到 spring**4 后 spring 推荐使用注解配置
IoC 注解(主要作用就是在 spring 容器中声明一个 Bean, 同 xml 中的 Bean 节点作用相同, 用在类上):
- @Repository(标识 DAO 层)
- @Service(标识 Service 层)
- @Conmpent(用在其他组件上)
隐式注入:
@Autowired: 根据类型注入
@Qualifier: 更具名字注入, 但是需要和 Autowired 连用
@Resource:jdk 提供, 默认根据名字注入, 如果没找到名字则根据类型注入
Aop 注解()
- @Aspect(作用在类上, 标识这是一个切面)
- @Before(作用在方法上, 前置增强)
- @AfterReturing(作用在方法上, 后置增强)
- @AfterThrowing(作用在方法上, 异常抛出增强)
- @After(作用在方法上, 最终增强)
其他注解
@Configuration: 标识作用, 表示这个类是一个核心配置类
@MapperScan: 扫描 Mapper 接口, 为 dao 层生成动态代理
@ComponentScan: 扫描有注解的类所在的包
@EnableTransactionManagement: 开启事务的注解
@EnableAspectJAutoProxy: 开启 aop 的注解
@Transactional 表示开启事务, 作用在类上为该类所有方法都开启一个事务, 也可以作用在方法上, 表示当前方法开启一个事务
1. 导入依赖
pom 节点砸死上一章 spring+mybatis 整合 (xml) 配置中有, 这里就不重复了.
2. 准备数据库
3. 业务代码
dao 层代码
- public interface AccountDao {
- List<Account>getAll();// 查询数据库中所有信息
- @Update("update account set accountmonkey=accountmonkey+1000 where accountid=1")
- int addMonkey();// 给 id 为 1 的用户加 1000 块钱
- @Update("update account set accountmonkey=accountmonkey-1000 where accountid=2")
- int subMonkey();// 给 id 为 2 的用户减 1000 块钱
- }
service 层接口
- public interface AccountService {
- List<Account> getAll();// 查询所有
- int changemonkey();// 模拟转账
- }
service 层实现类
- @Service
- public class AccountServiceImpl implements AccountService {
- // 注入 dao 接口实例
- @Autowired
- private AccountDao dao;
- @Override
- public List<Account> getAll() {
- return dao.getAll();
- }
- @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
- @Override
- public int changemonkey() {
- dao.subMonkey();//id 为 2 的先转出 1000
- //int reuslt=5/0;// 模拟一个异常, 中断交易
- dao.addMonkey();//id 为 1 的收到 1000
- return 0;
- }
- }
实体类(建完表一定要先写实体类)
- public class Account {
- private int accountid;
- private String accountname;
- private Double accountmonkey;
- // 省略 setter,getter
- }
4. 核心配置类
- package com.cn.config;
- import com.cn.advisor.AccountAdvisor;
- import org.apache.commons.dbcp2.BasicDataSource;
- import org.mybatis.spring.SqlSessionFactoryBean;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.EnableAspectJAutoProxy;
- import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- import javax.sql.DataSource;
- import java.beans.PropertyVetoException;
- import java.io.IOException;
- import java.NET.MalformedURLException;
- @Configuration// 指定这是一个核心配置类
- @MapperScan("com.cn.dao")// 扫描 dao 层, 生成动态代理
- @ComponentScan("com.cn")// 扫描该路径下所有类上的注解
- @EnableTransactionManagement// 开启事务
- @EnableAspectJAutoProxy
- public class ApplicationConfig {
- // 配置数据源
- @Bean// 等同于 xml 中的 < bean > 节点
- public DataSource dataSource(JdbcConfig dbcp) throws PropertyVetoException {
- // 其中 JdbcConfig 是自定义的配置类, 读取 properties 文件的类
- BasicDataSource cd = new BasicDataSource();
- cd.setDriverClassName(dbcp.getDriver());
- cd.setUrl(dbcp.getUrl());
- cd.setUsername(dbcp.getName());
- cd.setPassword(dbcp.getPassword());
- return cd;
- }
- // 配置核心 Mybatis 核心工厂
- @Bean
- public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource ds) throws IOException {
- SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
- bean.setDataSource(ds);// 配置数据源
- bean.setTypeAliasesPackage("com.cn.entity");// 设置实体类别名
- PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
- bean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));// 配置 Mapper 映射文件的路径
- return bean;
- }
- // 配置事务管理器
- @Bean
- public DataSourceTransactionManager dataSourceTransactionManager(DataSource ds){
- DataSourceTransactionManager dm = new DataSourceTransactionManager();
- dm.setDataSource(ds);
- return dm;
- }
- }
读取连接参数的配置类
- package com.cn.config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.PropertySource;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Repository;
- @Repository// 这里就是向证明一下 IoC 的几个声明 bean 的注解是可以混用的
- @PropertySource("classpath:/database.properties")
- public class JdbcConfig {
- @Value("${jdbc.username}")
- private String name;
- @Value("${jdbc.password}")
- private String password;
- @Value("${jdbc.driver}")
- private String driver;
- @Value("${jdbc.url}")
- private String url;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getDriver() {
- return driver;
- }
- public void setDriver(String driver) {
- this.driver = driver;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- }
切面
- @Aspect// 标志这是一个切面
- @Component// 和 @Service 作用一样, 都是在 spring 容器中声明一个 Bean
- public class AccountAdvisor {
- @Pointcut("execution(* com.cn.service.*.*(..))")
- public void pointcut(){}
- @Before("pointcut()")
- public void before(JoinPoint jp){
- System.out.println("我是前置增强!!!");
- }
- }
编写测试类
- public class App
- {
- public static void main( String[] args ) {
- ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
- AccountService bean = context.getBean(AccountService.class);
- System.out.println(bean.getAll());// 获取所有用户
- bean.changemonkey();// 模拟转账
- }
- }
将 service 层的算术异常的注释解开, 模拟一个异常, 可以验证事务是否能用!
Mybatis 与 Spring 整合(纯注解)
来源: http://www.bubuko.com/infodetail-2982760.html