用Aop代理就不用自己写代理对象,spring会自动生成代理对象。
下面用一个实例说明:
Person.java
package com.lx.spring.aop;
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PersonDao.java
package com.lx.spring.aop;
public interface PersonDao {
public void savePerson(Person person);
}
PersonDaoImpl.java
package com.lx.spring.aop;
public class PersonDaoImpl extends HibernateUitl implements PersonDao {
public void savePerson(Person person) {
sessionFactory.getCurrentSession().save(person);
}
}
HibernateUtil.java
package com.lx.spring.aop;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUitl {
public static SessionFactory sessionFactory;
static{
Configuration configuration = new Configuration();
configuration.configure("com/lx/spring/aop/hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
}
}
PersonTest.java
package com.lx.spring.aop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PersonTest {
@Test
public void test()
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDaoImpl personDao = (PersonDaoImpl) context.getBean("personDao");
Person person = new Person();
person.setName("mair");
personDao.savePerson(person);
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="personDao" class="com.lx.spring.aop.PersonDaoImpl"></bean>
<bean id="mytransaction" class="com.lx.spring.aop.MyTransaction"></bean>
<aop:config>
<aop:pointcut expression="execution(* com.lx.spring.aop.PersonDaoImpl.*(..))" id="perform"/>
<aop:aspect ref="mytransaction">
<aop:before method="beginTransaction" pointcut-ref="perform"/>
<aop:after-returning method="commit" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
</beans>
用debug可以查看spring采用哪种代理方式。
默认的采用:jdk代理
将PersonDaoImpl.java不实现PersonDao接口
采用cglib代理