报错如下
Bean named 'userServiceImpl' is expected to be of type 'com.atguigu.demo.tx.UserServiceImpl' but was actually of type 'com.sun.proxy.$Proxy13' at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:395) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
代码如下
测试类
public class TestTx {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("tx.xml");
UserService userServiceImpl = context.getBean("userServiceImpl", UserService.class);
userServiceImpl.accountMoney();
}
}
service层
public interface UserService {
int add(User user);
User getUserBId(String id);
//转账
void accountMoney();
}
serviceImpl层
@Service
//propagation 传播级别
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public int add(User user) {
int add = userDao.add(user);
System.out.println("add记录"+add);
return add;
}
@Override
public User getUserBId(String id) {
User user = userDao.getUserById(id);
return user;
}
/**
* 事务操作
*/
@Override
public void accountMoney() {
userDao.reduceMoney();
// int i=10/0;
userDao.addMoney();
}
}
报错原因
原来的错误写法
使用context获取bean的时候传入实现类的类型,代理类只能向上转型为接口类型,不能转成同等级UserServiceImpl。
修改测试类代码