由于存在JDK代理,导致UnsatisfiedDependencyException异常

时间:2019-07-05 10:27:10

标签: java spring dependency-injection spring-aop

我正在尝试使用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:创建名称为bean的错误   'myService':通过字段表示的不满意依赖性   “ myDaoRepository”;嵌套异常为   org.springframework.beans.factory.BeanNotOfRequiredTypeException:Bean   名为“ myDaoRepository”的类型应为   “ aop.question_005.dao.MyDaoRepository”,但实际上是类型   'com.sun.proxy。$ Proxy22'

我可以通过启用GCLIB机制来解决此问题,但是我想知道如何使用相同的JDK动态代理来解决此问题?

1 个答案:

答案 0 :(得分:1)

代码中的问题是您使用的是MyDaoRepository类而不是@Repository接口。您可以将代理转换为接口dao,但不能将其转换为接口的实现。您需要修改服务代码以使用接口:

dao