Spring(三)

一、Spring使用AspectJ进行AOP的开发:注解的方式
步骤一:引入相关的jar包:

  • spring的传统AOP的开发的包
    spring-aop-4.2.4.RELEASE.jar
    com.springsource.org.aopalliance-1.0.0.jar
  • aspectJ的开发包:
    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
    spring-aspects-4.2.4.RELEASE.jar

步骤二:引入Spring的配置文件

引入AOP约束:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
	
</beans>

步骤三:编写目标类:

public class ProductDao {
	public void save(){
		System.out.println("保存商品...");
	}
	public void update(){
		System.out.println("修改商品...");
	}
	public void delete(){
		System.out.println("删除商品...");
	}
	public void find(){
		System.out.println("查询商品...");
	}
}

步骤四:配置目标类(在Spring的配置文件中进行配置):

 <!-- 目标类============ -->
 <bean id="productDao" class="cn.itcast.spring.demo4.ProductDao"></bean>   

步骤五:开启aop注解的自动代理:

<aop:aspectj-autoproxy/>

步骤六:AspectJ的AOP的注解:
@Aspect:定义切面类的注解
通知类型:
* @Before :前置通知
* @AfterReturing :后置通知
* @Around :环绕通知
* @After :最终通知
* @AfterThrowing :异常抛出通知.

@Pointcut:定义切入点的注解
步骤七:编写切面类:

@Aspect
public class MyAspectAnno {

	@Before("MyAspectAnno.pointcut1()")
	public void before(){
		System.out.println("前置通知===========");
	}
	
	@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.save(..))")
	private void pointcut1(){}
}

1.2.1.8配置切面:

 <!-- 配置切面类 -->
 <bean id="myAspectAnno" class="cn.itcast.spring.demo4.MyAspectAnno"></bean>  

1.2.1.9其他通知的注解:

@Aspect
public class MyAspectAnno {

	@Before("MyAspectAnno.pointcut1()")
	public void before(){
		System.out.println("前置通知===========");
	}
	
	@AfterReturning("MyAspectAnno.pointcut2()")
	public void afterReturning(){
		System.out.println("后置通知===========");
	}
	
	@Around("MyAspectAnno.pointcut3()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("环绕前通知==========");
		Object obj = joinPoint.proceed();
		System.out.println("环绕后通知==========");
		return obj;
	}
	
	@AfterThrowing("MyAspectAnno.pointcut4()")
	public void afterThrowing(){
		System.out.println("异常抛出通知========");
	}
	
	@After("MyAspectAnno.pointcut4()")
	public void after(){
		System.out.println("最终通知==========");
	}
	
	@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.save(..))")
	private void pointcut1(){}
	@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.update(..))")
	private void pointcut2(){}
	@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.delete(..))")
	private void pointcut3(){}
	@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.find(..))")
	private void pointcut4(){}
}

利用Spring的JDBC模板完成数据的增删改查

Spring提供了很多持久层技术的模板类简化编程:
在这里插入图片描述
步骤一:创建数据库和表
步骤二:引入相关jar包
在这里插入图片描述
步骤三:创建一个测试类或者将连接池交给Spring管理

@Test
// JDBC模板的基本使用:
public void demo1(){
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	dataSource.setUrl("jdbc:mysql:///spring_day03");
	dataSource.setUsername("root");
	dataSource.setPassword("123");
	
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	jdbcTemplate.update("insert into account values (null,?,?)", "会希",10000d);
}

在Spring配置文件中配置连接池

【引入Spring的配置文件】

【配置内置连接池】
    <!-- 配置Spring的内置连接池 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    	<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    	<property name="url" value="jdbc:mysql:///spring_day02"/>
    	<property name="username" value="root"/>
    	<property name="password" value="123"/>
    </bean>
【将模板配置到Spring中】
    <!-- 配置JDBC模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    	<property name="dataSource" ref="dataSource"/>
    </bean>
【编写测试类】
**** 引入spring-aop.jar

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDemo2 {
	
	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void demo1(){
		jdbcTemplate.update("insert into account values (null,?,?)", "凤姐",10000d);
	}

}

Spring中的事务管理 Spring中的事务详解
spring事务中的API
PlatformTransactionManager:平台事务管理器.

***** 真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager	使用Spring JDBC或iBatis 进行持久化数据时使用
org.springframework.orm.hibernate3.HibernateTransactionManager		使用Hibernate版本进行持久化数据时使用

TransactionDefinition:事务定义信息
事务定义信息:

  • 隔离级别
  • 传播行为
  • 超时信息
  • 是否只读
    TransactionStatus:事务的状态
    记录事务的状态

Spring中的事务实例
创建业务层和DAO的类

public interface AccountService {

	public void transfer(String from,String to,Double money);
}

public class AccountServiceImpl implements AccountService {

	// 业务层注入DAO:
	private AccountDao accountDao;
	
	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}

	@Override
	/**
	 * from:转出的账号
	 * to:转入的账号
	 * money:转账金额
	 */
	public void transfer(String from, String to, Double money) {
		accountDao.outMoney(from, money);
		accountDao.inMoney(to, money);
	}

}
public interface AccountDao {

	public void outMoney(String from,Double money);
	
	public void inMoney(String to,Double money);
}

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

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

	@Override
	public void inMoney(String to, Double money) {
		this.getJdbcTemplate().update("update account set money = money + ? where name = ?", money,to);  
	}
          
}

配置业务层和DAO

 <!-- 配置业务层的类 -->
    <bean id="accountService" class="cn.itcast.transaction.demo1.AccountServiceImpl">
    	<property name="accountDao" ref="accountDao"/>
    </bean>
    
    <!-- 配置DAO的类 -->
    <bean id="accountDao" class="cn.itcast.transaction.demo1.AccountDaoImpl">
    	<property name="dataSource" ref="dataSource"/>
    </bean>

编写测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringDemo4 {
	
	@Resource(name="accountService")
	private AccountService accountService;
	
	@Test
	// 转账的测试:
	public void demo1(){
		accountService.transfer("会希", "凤姐", 1000d);
	}
}

Spring的编程式事务(了解)
手动编写代码完成事务的管理:
1.配置事务管理器

   <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   		 <property name="dataSource" ref="dataSource"/>
    </bean>

2.配置事务管理的模板

<!-- 配置事务管理模板 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
	<property name="transactionManager" ref="transactionManager"/>
</bean>

需要在业务层注入事务管理模板

<!-- 配置业务层的类 -->
<bean id="accountService" class="cn.itcast.transaction.demo1.AccountServiceImpl">
	<property name="accountDao" ref="accountDao"/>
	<!-- 注入事务管理模板 -->
	<property name="transactionTemplate" ref="transactionTemplate"/>
</bean>

手动编写代码实现事务管理

public void transfer(final String from, final String to, final Double money) {
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				accountDao.outMoney(from, money);
				int d = 1 / 0;
				accountDao.inMoney(to, money);			
			}
		});
	}

Spring的声明式事务管理XML方式(*****):思想就是AOP.
不需要进行手动编写代码,通过一段配置完成事务管理
引入AOP开发的包
aop联盟.jar
Spring-aop.jar
aspectJ.jar
spring-aspects.jar

恢复转账环境

配置事务管理器

<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
</bean>

配置事务的通知

<!-- 配置事务的增强 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
	  <!-- 
			isolation="DEFAULT"		隔离级别
			propagation="REQUIRED"	传播行为
			read-only="false"	只读
			timeout="-1"		过期时间
			rollback-for=""		-Exception
			no-rollback-for=""	+Exception
		 -->
		<tx:method name="transfer" propagation="REQUIRED"/>
	</tx:attributes>
</tx:advice>

配置aop事务

<aop:config>
	<aop:pointcut expression="execution(* cn.itcast.transaction.demo2.AccountServiceImpl.transfer(..))" id="pointcut1"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
</aop:config>

Spring的声明式事务的注解方式: (*****)
引入jar包:
在这里插入图片描述
恢复转账环境:

配置事务管理器:

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
</bean>

开启事务管理的注解:

<!-- 开启注解事务管理 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

在使用事务的类上添加一个注解:@Transactional
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值