简体   繁体   中英

Spring Boot: The bean 'auditLogDao' could not be injected as a 'AuditLogDao' because it is a JDK dynamic proxy

I am getting the following error in a Spring Boot project on which I work:

The bean 'auditLogDao' could not be injected as a '{redactedpathwithcorporatename}.AuditLogDao' because it is a JDK dynamic proxy that implements: org.springframework.data.jpa.repository.JpaRepository

Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

I have tried a variety of solutions on StackOverflow without success, specifically:

  1. Checking that I am indeed calling the interface, not the implementation.

  2. Adding @Component to the top of SwitchUserFilter

  3. Changing @Resource to @Autowired.

AuditLogDao.java

public interface AuditLogDao extends JpaRepository<AuditLog, String> {}

AuditLogService.java

public interface AuditLogService {
    AuditLog save(final AuditLog auditLog);
}

AuditLogServiceImplementation.java

public class AuditLogServiceImplementation implements AuditLogService{

    @Resource private AuditLogDao auditLogDao;

    @Override
    public AuditLog save(AuditLog auditLog) {
        return auditLogDao.save(auditLog);
    }
}

The file where I actually want to use the service to save information

SwitchuserFilter.java

public class SwitchUserFilter
        extends org.springframework.security.web.authentication.switchuser.SwitchUserFilter {
    @Resource AuditLogService logService;
'''
        logService.save(auditLog);
'''
}

I am relatively new to Spring Boot, so an explanation of why it fixes the problem would be appreciated.

I believe the following code will solve your problem. Add it to the AuditLogServiceImplementation and remove the @Resource annotation from the auditLogDao.

@Autowired
private ListableBeanFactory beanFactory;

@EventListener({ContextRefreshedEvent.class})
void contextRefreshedEvent() {
    auditLogDao = beanFactory.getBean(AuditLogDao.class);
}

You can do a similar trick in the filter too, whatever more comfortable for you.

I don't know what is the exact problem, but it's some kind of circular-dependency-like issue. So by manually importing any bean which is affected in this loop, you can resolve the loop. You will set this one particular dependency AFTER Spring had created all of the other beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM