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整合(纯注解)的更多相关文章

  1. Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来

    转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...

  2. Mybatis第五篇【Mybatis与Spring整合】

    Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...

  3. MyBatis 与 Spring 整合

    MyBatis-Spring 项目 目前大部分的 Java 互联网项目,都是用 Spring MVC + Spring + MyBatis 搭建平台的. 使用 Spring IoC 可以有效的管理各类 ...

  4. mybatis与spring整合配置

    mybatis与spring整合配置: 第一种方式:(此处配置扫描的包路径.注解.每个mapper类上面需要加@Repository才能纳入spring的bean管理器中) <!-- 自动扫描m ...

  5. MyBatis和Spring整合案例

    1.所需要导入的jar文件 !--MyBatis和Spring的整合包 由MyBatis提供--> <dependency> <groupId>org.mybatis&l ...

  6. MyBatis和Spring整合的奥秘

    本篇博客源码分析基于Spring 5.1.16.RELEASE,mybatis-spring 2.0.0,较高版本的mybatis-spring源码有较大区别. Spring之所以是目前Java最受欢 ...

  7. spring boot纯注解开发模板

    简介 spring boot纯注解开发模板 创建项目 pom.xml导入所需依赖 点击查看源码 <dependencies> <dependency> <groupId& ...

  8. 手写Mybatis和Spring整合简单版示例窥探Spring的强大扩展能力

    Spring 扩展点 **本人博客网站 **IT小神 www.itxiaoshen.com 官网地址****:https://spring.io/projects/spring-framework T ...

  9. MyBatis学习(四)MyBatis和Spring整合

    MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...

  10. Mybatis+struts2+spring整合

    把student项目改造成ssm  struts2 +mybatis+spring 1,先添加spring支持:类库三个,applicationContext.xml写在webinf下四个命名空间,监 ...

随机推荐

  1. RNA组研究困难

    RNA组研究的困难何在?如果开发新技术来解决这些困难,您最想解决的科学问题是什么? RNA研究的困难在于研究技术落后 (1)从信息流来说,我们需要直接测定RNA的序列,但是我们只能DNA测序仪间接测得 ...

  2. [极客大挑战 2019]Http

    0x00知识点 了解HTTP协议,使用bp伪造. 0x01 解题 首先查看源代码,找到Secret.php 访问 使用bp查看 提示我们需要来自该网址,直接改header头信息即可,我们可以通过使用r ...

  3. JaveSE--getResource

    System.out.println(ConfigUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath()); ...

  4. nginx常用编译参数

    ./configurate --prefix=/app/tengine --user=www --group=www --with-http_v2_module --with-http_ssl_mod ...

  5. 6.react 基础 - 关于 react 开发 的原则

    1. 声明式开发 通过绑定元素 在数据变更时 对元素进行动态渲染 2. 可以与其他框架并存 不在React的绑定元素内, 可以使用其他框架 如 ( vue jQuery 等 ) 进行元素操作 3. 组 ...

  6. How to .gitignore all files/folder in a folder, but not the folder itself?

    https://stackoverflow.com/questions/4250063/how-to-gitignore-all-files-folder-in-a-folder-but-not-th ...

  7. Linux中的错误重定向你真的懂吗

    在很多定时任务里.shell里我们往往能看到 "2>&1",却不知道这背后的原理. 举个例子: * 1 * * * test.sh > /dev/null 2& ...

  8. ZJNU 1160 - 不要62——中级

    取模判断,数组模拟 /* Written By StelaYuri */ #include<stdio.h> ]; int main(){ int n,m,i,s,t; ;i<;i+ ...

  9. 并发与高并发(四)-java并发的优势和风险

  10. 使用conda管理python环境

    一.动机 最近打算折腾vn.py,但只有py27版本的,因为一向习惯使用最新稳定版的,所以不得不装py27的环境,不得不说 Python的全局锁真的很烦. 身为懒癌患者,必然使用全功能的anacond ...