开发步骤
①开启支持AOP注解
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.atguigu">context:component-scan>
<aop:aspectj-autoproxy>aop:aspectj-autoproxy>
beans>
②制作目标对象类
@Service
public class UserServiceImpl implements UserService {
@Override
public void addUser() throws Exception {
System.out.println("UserServiceImpl addUser");
System.out.println(1 / 0);
}
@Override
public void deleteUser() throws Exception {
System.out.println("UserServiceImpl deleteUser");
}
}
③制作通知类
@Aspect
@Component
public class MyAdvice01 {
@Before("execution(* *..*Service.addUser())")
public void before(){
System.out.println("MyAdvice01 before");
}
@AfterReturning("execution(* *..*Service.addUser())")
public void afterReturning(){
System.out.println("MyAdvice01 afterReturning");
}
@AfterThrowing("execution(* *..*Service.addUser())")
public void afterThrowing(){
System.out.println("MyAdvice01 afterThrowing");
}
@After("execution(* *..*Service.addUser())")
public void after(){
System.out.println("MyAdvice01 after");
}
@Around("execution(* *..*Service.addUser())")
public void around(ProceedingJoinPoint pjp){
System.out.println("MyAdvice01 around之前");
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("MyAdvice01 around之后");
}
}
分类
代码实现
@Aspect
@Component
public class MyAdvice02 {
@Around("execution(* *..*Service.*(..))")
public void around(ProceedingJoinPoint pjp) {
Object[] args = pjp.getArgs();
System.out.println("MyAdvice02 around" + Arrays.toString(args));
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Before("execution(* *..*Service.*(..))")
public void before(JoinPoint jp){
Object[] args = jp.getArgs();
System.out.println("MyAdvice02 before" + Arrays.toString(args));
}
}
概述
代码实现
@Aspect
@Component
public class MyAdvice03 {
@Around("execution(* *..*Service.*(..))")
public Object around(ProceedingJoinPoint pjp) {
try {
Object result = pjp.proceed();
System.out.println("MyAdvice03 around " + result);
return result;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
@AfterReturning(value = "execution(* *..*Service.*(..))",returning = "result")
public void afterReturning(Object result){
System.out.println("MyAdvice03 afterReturning " + result);
}
}
概述
代码实现
@Aspect
@Component
public class MyAdvice04 {
@Around("execution(* *..*Service.*(..))")
public void around(ProceedingJoinPoint pjp) {
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
System.out.println("MyAdvice04 around " + e);
throw new RuntimeException(e);
}
}
@AfterThrowing(value = "execution(* *..*Service.*(..))" , throwing = "e")
public void afterThrowing(Exception e){
System.out.println("MyAdvice04 afterThrowing " + e);
}
}
需求
总结
需求
代码实现
@Service
public class UserServiceImpl2 {
public String addUser(int num) throws Exception {
System.out.println("UserServiceImpl2 addUser " + num);
//System.out.println(1 / 0);
return "helloworld";
}
public void deleteUser() throws Exception {
System.out.println("UserServiceImpl2 deleteUser");
}
}
@Aspect
@Component
public class MyAdvice06 {
@Before("execution(* *..UserServiceImpl2.*(..))")
public void before(){
System.out.println("MyAdvice06 before");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-core.xml")
public class UserServiceImpl2Test {
@Autowired
private UserServiceImpl2 userServiceImpl2;
@Test
public void addUser() throws Exception {
userServiceImpl2.addUser(250);
}
@Test
public void deleteUser() {
}
}
总结
有接口
没接口
开发步骤
①引入相关依赖
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<junit.version>4.13.2junit.version>
<lombok.version>1.18.22lombok.version>
<spring.version>5.3.13spring.version>
<dbutils.version>1.7dbutils.version>
<druid.version>1.2.8druid.version>
<mysql.version>5.1.48mysql.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jclartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.7version>
dependency>
<dependency>
<groupId>aopalliancegroupId>
<artifactId>aopallianceartifactId>
<version>1.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
dependencies>
②定义dao接口及其实现子类
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void addUser(User inputUser) throws Exception {
jdbcTemplate.update(
"insert into tb_user values(null,?,?,?)",
inputUser.getUserName(),
inputUser.getUserPwd(),
inputUser.getMoney()
);
}
@Override
public void deleteUser(Integer userId) throws Exception {
jdbcTemplate.update(
"delete from tb_user where user_id = ?",
userId
);
}
@Override
public void updateUser(User inputUser) throws Exception {
jdbcTemplate.update(
"update tb_user set user_name = ? , user_pwd = ? , money = ? where user_id = ?",
inputUser.getUserName(),
inputUser.getUserPwd(),
inputUser.getMoney(),
inputUser.getUserId()
);
}
@Override
public User selectUserById(Integer userId) throws Exception {
String sql = "select * from tb_user where user_id = ?";
RowMapper<? extends User> rowMapper = new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setUserId(resultSet.getInt("user_id"));
user.setUserName(resultSet.getString("user_name"));
user.setUserPwd(resultSet.getString("user_pwd"));
user.setMoney(resultSet.getDouble("money"));
return user;
}
};
return jdbcTemplate.queryForObject(
sql,
rowMapper,
userId
);
}
@Override
public List<User> selectUserList() throws Exception {
return jdbcTemplate.query(
"select user_id userId,user_name userName , user_pwd userPwd ,money money from tb_user",
new BeanPropertyRowMapper<>(User.class)
);
}
}
③编写spring-core.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">property>
bean>
<context:property-placeholder location="jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}">property>
<property name="url" value="${url}">property>
<property name="username" value="${user}">property>
<property name="password" value="${password}">property>
bean>
beans>
④代码测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-core.xml")
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Test
public void addUser() throws Exception {
userDao.addUser(new User(1,"zhangsan","zhangsan",10000.0));
}
@Test
public void deleteUser() {
}
@Test
public void updateUser() {
}
@Test
public void selectUserById() throws Exception {
User user = userDao.selectUserById(52);
System.out.println("user = " + user);
}
@Test
public void selectUserList() throws Exception {
List<User> userList = userDao.selectUserList();
System.out.println("userList = " + userList);
}
}
需求
开发步骤
①定义service及其实现子类
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
//出账
userDao.outMoney(outName, money);
System.out.println(1 / 0);
//入账
userDao.inMoney(inName, money);
}
}
②定义dao及其实现子类
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void outMoney(String outName, Double money) throws Exception {
jdbcTemplate.update(
"update tb_user set money = money - ? where user_name = ?",
money,
outName
);
}
@Override
public void inMoney(String inName, Double money) throws Exception {
jdbcTemplate.update(
"update tb_user set money = money + ? where user_name = ?",
money,
inName
);
}
}
③代码测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-core.xml")
public class UserServiceTest {
@Autowired
private UserServiceImpl userService;
@Test
public void transfer() throws Exception {
userService.transfer("zhangsan", "lisi", 100.0);
}
}
概述
开发步骤
①编写spring-core.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
//....
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<bean id="definition1" class="org.springframework.transaction.support.DefaultTransactionDefinition">
<property name="readOnly" value="false">property>
bean>
<bean id="definition2" class="org.springframework.transaction.support.DefaultTransactionDefinition">
<property name="readOnly" value="true">property>
bean>
beans>
②改造UserServiceImpl代码
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private DataSourceTransactionManager transactionManager;
@Autowired
@Qualifier("definition1")
private TransactionDefinition definition;
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
TransactionStatus status = null;
try {
//开启事务
status = transactionManager.getTransaction(definition);
//出账
userDao.outMoney(outName, money);
System.out.println(1 / 0);
//入账
userDao.inMoney(inName, money);
//没有异常就提交事务
transactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
//有异常就回滚事务
transactionManager.rollback(status);
}
}
}
存在问题
概述
开发步骤
①自定义MyTransactionManager工具类
@Component
public class MyTransactionManager {
@Autowired
private DataSourceTransactionManager transactionManager;
@Autowired
@Qualifier("definition1")
private DefaultTransactionDefinition definition;
/**
* 开启事务
*/
public TransactionStatus startTransaction(){
TransactionStatus status = transactionManager.getTransaction(definition);
return status;
}
/**
* 提交事务
* @param status
*/
public void commit(TransactionStatus status){
transactionManager.commit(status);
}
/**
* 回滚事务
* @param status
*/
public void rollback(TransactionStatus status){
transactionManager.rollback(status);
}
}
②改造UserServiceImpl代码
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private MyTransactionManager transactionManager;
@Override
public String addUser(int num) throws Exception {
System.out.println("UserServiceImpl addUser " + num);
//System.out.println(1 / 0);
return "helloworld";
}
@Override
public void deleteUser() throws Exception {
try {
System.out.println("UserServiceImpl deleteUser");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
TransactionStatus status = null;
try {
//开启事务
status = transactionManager.startTransaction();
//出账
userDao.outMoney(outName, money);
//System.out.println(1 / 0);
//入账
userDao.inMoney(inName, money);
//没有异常就提交事务
transactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
//有异常就回滚事务
transactionManager.rollback(status);
}
}
}
存在问题
概述
开发步骤
①定义事务通知类TxAdvice
@Component
public class TxAdvice {
@Autowired
private MyTransactionManager transactionManager;
@Autowired
@Qualifier("definition1")
private TransactionDefinition definition1;
/**
* DML的事务通知
* @param pjp
*/
public void dmlAround(ProceedingJoinPoint pjp) {
TransactionStatus status = null;
//开启事务
try {
status = transactionManager.startTransaction(definition1);
pjp.proceed();
transactionManager.commit(status);
} catch (Throwable e) {
e.printStackTrace();
transactionManager.rollback(status);
}
}
@Autowired
@Qualifier("definition2")
private TransactionDefinition definition2;
/**
* DQL的事务通知
* @param pjp
*/
public void dqlAround(ProceedingJoinPoint pjp){
TransactionStatus status = null;
//开启事务
try {
status = transactionManager.startTransaction(definition2);
pjp.proceed();
transactionManager.commit(status);
} catch (Throwable e) {
e.printStackTrace();
transactionManager.rollback(status);
}
}
}
②编写spring-core.xml
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<bean id="definition1" class="org.springframework.transaction.support.DefaultTransactionDefinition">
<property name="readOnly" value="false">property>
bean>
<bean id="definition2" class="org.springframework.transaction.support.DefaultTransactionDefinition">
<property name="readOnly" value="true">property>
bean>
<aop:config>
<aop:aspect ref="txAdvice">
<aop:around method="dmlAround" pointcut="execution(* *..*Service.transfer(..))">aop:around>
<aop:around method="dmlAround" pointcut="execution(* *..*Service.deleteUser(..))">aop:around>
<aop:around method="dmlAround" pointcut="execution(* *..*Service.addUser(..))">aop:around>
<aop:around method="dqlAround" pointcut="execution(* *..*Service.selectUser(..))">aop:around>
aop:aspect>
aop:config>
开发步骤
①编写spring-core.xml
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transfer" read-only="false"/>
<tx:method name="selectUserList" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Service.*(..))">aop:advisor>
aop:config>
常用属性
代码实现
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transfer" read-only="false" isolation="REPEATABLE_READ" timeout="10" propagation="REQUIRED" />
<tx:method name="select*" read-only="true" isolation="REPEATABLE_READ" timeout="10" propagation="REQUIRED"/>
<tx:method name="add*" read-only="false" isolation="REPEATABLE_READ" timeout="10" propagation="REQUIRED"/>
<tx:method name="delete*" read-only="false" isolation="REPEATABLE_READ" timeout="10" propagation="REQUIRED"/>
<tx:method name="update*" read-only="false" isolation="REPEATABLE_READ" timeout="10" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Service.*(..))">aop:advisor>
aop:config>
开发步骤
①编写spring-core.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">property>
bean>
<context:property-placeholder location="jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}">property>
<property name="url" value="${url}">property>
<property name="username" value="${user}">property>
<property name="password" value="${password}">property>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:annotation-driven transaction-manager="transactionManager">tx:annotation-driven>
beans>
②改造UserServiceImpl
@Transactional(readOnly = false, isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, timeout = 10)
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Transactional(readOnly = true)
@Override
public List<User> selectUserList() throws Exception {
return userDao.selectUserList();
}
@Override
public String addUser(int num) throws Exception {
System.out.println("UserServiceImpl addUser " + num);
//System.out.println(1 / 0);
return "helloworld";
}
@Override
public void deleteUser() throws Exception {
System.out.println("UserServiceImpl deleteUser");
}
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
userDao.outMoney(outName, money);
System.out.println(1 / 0);
userDao.inMoney(inName, money);
}
}
概述
代码实现
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Transactional(readOnly = true)
@Override
public List<User> selectUserList() throws Exception {
return userDao.selectUserList();
}
@Transactional(readOnly = false)
@Override
public String addUser(User inputUser) throws Exception {
//System.out.println(1 / 0);
userDao.addUser(inputUser);
return "helloworld";
}
@Override
public void deleteUser() throws Exception {
System.out.println("UserServiceImpl deleteUser");
}
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
userDao.outMoney(outName, money);
System.out.println(1 / 0);
userDao.inMoney(inName, money);
}
}
注意事项
概述
代码实现
@Transactional(readOnly = false,timeout = 5)
@Override
public String addUser(User inputUser) throws Exception {
//操作数据库之前超时,有效
Thread.sleep(6000);
userDao.addUser(inputUser);
//操作数据库之后超时,无效
//Thread.sleep(6000);
return "helloworld";
}
注意事项
userDao.selectUserList();
}
@Transactional(readOnly = false)
@Override
public String addUser(User inputUser) throws Exception {
//System.out.println(1 / 0);
userDao.addUser(inputUser);
return "helloworld";
}
@Override
public void deleteUser() throws Exception {
System.out.println("UserServiceImpl deleteUser");
}
@Override
public void transfer(String outName, String inName, Double money) throws Exception {
userDao.outMoney(outName, money);
System.out.println(1 / 0);
userDao.inMoney(inName, money);
}
}
注意事项
概述
代码实现
@Transactional(readOnly = false,timeout = 5)
@Override
public String addUser(User inputUser) throws Exception {
//操作数据库之前超时,有效
Thread.sleep(6000);
userDao.addUser(inputUser);
//操作数据库之后超时,无效
//Thread.sleep(6000);
return "helloworld";
}
注意事项