j2EE spring(AOP)

本文详细介绍了面向切面编程(AOP)的概念及其在Spring框架中的应用,包括如何通过注解实现事务管理,并展示了具体的XML配置及代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AOP

面向切面编程Aspect-Oriented-Programming,是对面向对象的思维方式的有力补充

可以动态的添加和删除在切面上的逻辑而不影响原来的执行代码

a)     Filter

b)     Struts2的interceptor

动态代理:

http://my.oschina.net/hnuweiwei/blog/290041


AOP

Annotation

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.bjsxt"/>
 	<aop:aspectj-autoproxy />
</beans>

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {
	@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
	public void myMethod(){};
	
	@Before("myMethod()")
	public void before() {
		System.out.println("method before");
	}
	
	@Around("myMethod()")
	public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("method around start");
		pjp.proceed();
		System.out.println("method around end");
	}
}

JoinPoint  释意:切面与原方法交接点 即 切入点

PointCut  释意:切入点集合

Aspect(切面)释意:可理解为代理类前说明(简单的理解为夹在类的新的业务逻辑,就是业务逻辑类)

Advice 释意:可理解为代理方法前说明 例如@Before(即加在切面上的说明)

Target  释意:被代理对象 被织入对象

Weave  释意:织入

XML配置

<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
    <aop:config>
        <!-- 配置一个切面 -->
        <aop:aspect id="point" ref="logInterceptor">
            <!-- 配置切入点,指定切入点表达式 -->
            <!-- 此句也可放到 aop:aspect标签外 依然有效-->
            <aop:pointcut  expression="execution(public * com.bjsxt.service..*.*(..))" id="myMethod" />
            <!-- 应用前置通知 -->
            <aop:before method="before" pointcut-ref="myMethod" />
            <!-- 应用环绕通知 需指定向下进行 -->
            <aop:around method="around" pointcut-ref="myMethod" />
            <!-- 应用后通知 -->
            <aop:after-returning method="afterReturning" pointcut-ref="myMethod" />
            <!-- 应用抛出异常后通知 -->
            <aop:after-throwing method="afterThrowing" pointcut-ref="myMethod" />
            <!-- 应用最终通知  -->
            <aop:after method="afterFinily"  pointcut="execution(public * om.bjsxt.service..*.*(..))" />
        </aop:aspect>
</aop:config>


Spring整合hibernate

<?xml version="1.0" encoding="UTF-8"?>
<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/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.bjsxt" />

	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.bjsxt.model.User</value>
				<value>com.bjsxt.model.Log</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager"> //事务管理方式
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<tx:annotation-driven transaction-manager="txManager"/> //事务管理驱动
</beans>

@Component("logDAO") 
public class LogDAOImpl implements LogDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void save(Log log) {
		
		Session s = sessionFactory.getCurrentSession();
		s.save(log);
		//throw new RuntimeException("error!");
	}

}
}

@Component("userService")
public class UserService {
	
	private UserDAO userDAO;
	private LogDAO logDAO;
	
	public void init() {
		System.out.println("init");
	}
	
	public User getUser(int id) {
		return null;
	}
	
	@Transactional(readOnly=true) //发生运行错误,自动回滚
	public void add(User user) {
			userDAO.save(user);
			Log log = new Log();
			log.setMsg("a user saved!");
			logDAO.save(log);
		
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="u")
	public void setUserDAO( UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	

	
	public LogDAO getLogDAO() {
		return logDAO;
	}
	
	@Resource
	public void setLogDAO(LogDAO logDAO) {
		this.logDAO = logDAO;
	}

	public void destroy() {
		System.out.println("destroy");
	}
}

在需要事务的方法上加:@Transactional。需要注意,Hibernate获得session时要使用SessionFactory.getCurrentSession 不能使用OpenSession

@Transactional详解

i. 什么时候rollback 

1. 运行期异常,非运行期异常不会触发rollback

2. 必须uncheck (没有catch)

3. 不管什么异常,只要你catch了,spring就会放弃管理

4. 事务传播特性:propagation_required(propagation是一个enum,默认值是required!唯一需要记住的)

例如: @Transactional(propagation=Propagation.REQUIRED)等同于(@Transactional)作用,一个方法声明了@Transactional事务后,其内再调用的方法不需要再声明@Transactional.



转载于:https://my.oschina.net/hnuweiwei/blog/297759

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值