JDK动态代理是通过java.lang.reflect.Proxy 类来实现的,我们可以调用Proxy类的newProxyInstance()方法来创建代理对象。对于使用业务接口的类,Spring默认会使用JDK动态代理来实现AOP。JDK的动态代理用起来非常简单,但它是有局限性的,使用动态代理的对象必须实现一个或多个接口。
CGLIB(Code Generation Library)是一个高性能开源的代码生成包,它采用非常底层的字节码技术,对指定的目标类生成一个子类,并对子类进行增强。
在实际运用中,如果代理的类实现了一个或多个接口,那么在拿bean时,必须通过接口来拿,如果没有实现接口,可以直接拿这个类本身
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//转账功能
@Transactional
public void Transfer(int out, int in,double money) {
//转出
jdbcTemplate.update("UPDATE account set balance=balance-? WHERE id=?", money,out);
//异常,运行到这里时需要事务管理器进行事务回滚
int i = 1/0;
//转入
jdbcTemplate.update("UPDATE account set balance=balance+? WHERE id=?", money,in);
}
}
public interface AccountDao {
public void Transfer(int out, int in,double money);
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao userDao = context.getBean(AccountDao.class);
userDao.Transfer(1, 2, 50);
如上,当AccountDaoImpl类实现了接口AccountDao时,如果在getBean时拿AccountDaoImpl,则会报错,错误信息为
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.creatorblue.jdbc.AccountDaoImpl' available
原因就是AccountDaoImpl类实现了接口AccountDao,spring默认会使用JDK代理,因此在getBean时,需要拿AccountDaoImpl的接口AccountDao,反过来,如果AccountDaoImpl没有实现接口,则可以直接拿其本身,即AccountDaoImpl