![](/img/trans.png)
[英]Spring MVC to SpringBoot 2: The bean 'xyz' could not be injected as a 'com..Abc' because it is a JDK dynamic proxy that implements:
[英]UnsatisfiedDependencyException because of the JDK proxy
我正在嘗試使用Spring提供的默認aop代理,但是卻遇到執行錯誤。
這是我的代碼:運行測試示例的第一類。
@EnableAspectJAutoProxy()
@ComponentScan(basePackageClasses = {MyDaoRepository.class, MyService.class,MyAdvices.class})
@Configuration
public class SpringAdvices {
public static void main( String[] args ) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringAdvices.class);
service myService = ctx.getBean(MyService.class);
Person p1 = (Person) ctx.getBean("person");
myService.save(p1);
}
@Bean
public Person person(){
return Person.builder()
.name("Bagna")
.age(52)
.profession(null)
.dateOfBirth(LocalDate.of(1950,12,13))
.build();
}
}
代表我的建議的第二堂課:
@Aspect
@Component
public class MyAdvices {
@Before("execution(boolean *.dao.save(..))")
public void beforesavamethod(){
System.out.println("beforesavamethod");
}
@After("execution(boolean *.dao.save(..))")
public void aftersavamethod(){
System.out.println("aftersavamethod");
}
}
我的服務和存儲庫類:
@Service
public class MyService implements service {
@Autowired
MyDaoRepository myDaoRepository;
@Override
public boolean save( Person person ){
return this.myDaoRepository.save(person);
}
@Override
public boolean delete(Person person){
return this.myDaoRepository.delete(person);
}
}
public interface service {
public boolean save( Person person );
public boolean delete( Person person );
}
@Repository
public class MyDaoRepository implements dao {
List<Person> personList = new ArrayList<>();
@Override
public boolean save( Person person ){
return this.personList.add(person);
}
@Override
public boolean delete( Person person ){
return this.personList.remove(person);
}
}
public interface dao {
public boolean save( Person person );
public boolean delete( Person person );
}
我正在關注的例外是將dao對象注入到服務對象中。
UnsatisfiedDependencyException:創建名稱為“ myService”的bean時出錯:通過字段“ myDaoRepository”表示的不滿足的依賴關系; 嵌套的異常是org.springframework.beans.factory.BeanNotOfRequiredTypeException:名為“ myDaoRepository”的Bean的類型應為“ aop.question_005.dao.MyDaoRepository”,但實際上其類型為“ com.sun.proxy。$ Proxy22”
我可以通過啟用GCLIB機制來解決此問題,但是我想知道如何使用相同的JDK動態代理解決此問題?
代碼中的問題是您正在使用類MyDaoRepository而不是dao
接口。 您可以將代理轉換為接口dao,但不能將其轉換為接口的實現。 您需要修改服務代碼以使用接口:
@Service
public class MyService implements service {
@Autowired
dao myDaoRepository;
@Override
public boolean save( Person person ){
return this.myDaoRepository.save(person);
}
@Override
public boolean delete(Person person){
return this.myDaoRepository.delete(person);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.