springJDK代理和CGLIB代理使用时的规则

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值