使用junit测试ssh搭建的框架的时候,遇到了一个异常:
异常消息:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.htd.test.Test1':
Injection of resource dependencies failed;nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'registerService' must be of type [com.htd.service.impl.RegisterServiceImpl], but was actually of type [com.sun.proxy.$Proxy42]测试类代码:
1 package com.htd.test; 2 3 import javax.annotation.Resource; 4 import org.junit.Test; 5 import org.junit.runner.RunWith; 6 import org.springframework.test.context.ContextConfiguration; 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 import com.htd.domain.Customer; 9 import com.htd.service.impl.RegisterServiceImpl;10 11 @RunWith(SpringJUnit4ClassRunner.class)12 @ContextConfiguration("classpath:applicationContext.xml")13 public class Test1 {14 @Resource(name="registerService")15 private RegisterServiceImpl registerService;16 17 @Test18 public void test1() {19 Customer customer=new Customer();20 customer.setCus_name("eastry");21 customer.setCus_email("123456@qq.com");22 customer.setCus_pwd("123");23 customer.setCus_id(1);24 registerService.save(customer);25 }26 27 }
RegisterServiceImpl类:
1 package com.htd.service.impl; 2 3 import org.springframework.transaction.annotation.Transactional; 4 5 import com.htd.dao.impl.CustomerDaoImpl; 6 import com.htd.domain.Customer; 7 import com.htd.service.IRegisterService; 8 9 @Transactional10 public class RegisterServiceImpl implements IRegisterService {11 //xml方式注入12 private CustomerDaoImpl customerDao;13 public void setCustomerDao(CustomerDaoImpl customerDao) {14 this.customerDao = customerDao;15 }16 @Override17 public void save(Customer customer) {18 customerDao.save(customer);19 }20 }
RegisterServiceImpl的接口IRegisterService:
1 import com.htd.domain.Customer;2 3 public interface IRegisterService {4 public void save(Customer customer);5 }
运行结果:
不好,红了。。。。。
这里没有使用Cglib代理,Java的动态代理是使用接口实现的,但是在Test类里面注入的时候是使用Service的实现类(即:RegisterServiceImpl)注入的,所以这里会出错。
如图:
修改成下列代码测试成功:
修改后的测试类代码:
1 import javax.annotation.Resource; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.test.context.ContextConfiguration; 6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 7 8 import com.htd.domain.Customer; 9 import com.htd.service.IRegisterService;10 @RunWith(SpringJUnit4ClassRunner.class)11 @ContextConfiguration("classpath:applicationContext.xml")12 public class Test1 {13 @Resource(name="registerService")14 private IRegisterService registerService;15 16 @Test17 public void test1() {18 Customer customer=new Customer();19 customer.setCus_name("eastry");20 customer.setCus_email("123456@qq.com");21 customer.setCus_pwd("123");22 customer.setCus_id(1);23 registerService.save(customer);24 }25 }
运行结果:
嗯,变绿了,很好。。。。。。。。。。。
如果想用类注入,就要导入Cglib的jar包 使用类来实现代理????请大佬指导,我还没试试,之后会去实验下。