복붙노트

[SPRING] 왜 @Transactional 메서드가있는 클래스는 자동 실행되지 않을 수 있습니까?

SPRING

왜 @Transactional 메서드가있는 클래스는 자동 실행되지 않을 수 있습니까?

Active Directory 서버에 대해 사용자를 인증하는 WAFFLE 필터와 함께 Spring Security를 ​​사용하고 있습니다. 내 데이터베이스에 대해 사용자를 인증하는 추가 필터를 만들었습니다. 이전에 인증 된 사용자가 데이터베이스에 있음). 이는 UserDetailsService 구현을 사용하여 수행됩니다.

이 조합은 서비스에 @Transactional 주석이 추가 된 메소드를 추가 할 때까지 작동했습니다. 지금 서비스 필터에 자동으로 연결할 수 없습니다.

다음은 서비스 클래스입니다.

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LdapUserDao ldapUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return getUserByUsername(username);
    }

    public User getUserByUsername(final String username) {
        final User databaseUser = userRepository.findByUsername(username);
        final User ldapUser = ldapUserDao.findByUsername(username);

        if (null == databaseUser || null == ldapUser) {
            return null;
        }

        final User user = mergeUsers(databaseUser, ldapUser);

        return user;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Transactional
    public void storeUser(final User user) {
        userRepository.save(user);
    }

    private User mergeUsers(final User database, final User ldap) {
        final User mergedUser = new User();

        mergedUser.setId(database.getId());
        mergedUser.setUsername(database.getUsername());
        mergedUser.setEnabled(database.isEnabled());
        mergedUser.setRoles(database.getRoles());

        mergedUser.setEmail(ldap.getEmail());
        mergedUser.setFirstName(ldap.getFirstName());
        mergedUser.setLastName(ldap.getLastName());
        mergedUser.setLocale(ldap.getLocale());

        return mergedUser;
    }

}

그리고 이것이 필터입니다.

public class WaffleAuthenticationWrapperFilter extends GenericFilterBean {

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        final SecurityContext securityContext = SecurityContextHolder.getContext();
        final Authentication authentication = securityContext.getAuthentication();

        if (null == authentication || !(authentication instanceof WindowsAuthenticationToken)) {
            chain.doFilter(request, response);
            return;
        }

        final WindowsAuthenticationToken waffleAuthentication = (WindowsAuthenticationToken) authentication;
        final String username = waffleAuthentication.getName().replaceAll("^.*\\\\", "");
        final User user = userService.getUserByUsername(username);

        if (null == user) {
            securityContext.setAuthentication(null);
            return;
        }

        final WaffleAuthenticationWrapper authenticationWrapper = new WaffleAuthenticationWrapper(waffleAuthentication,
                user);

        securityContext.setAuthentication(authenticationWrapper);

        chain.doFilter(request, response);
    }

}

@Transactional을 제거하자마자 프로젝트가 다시 컴파일됩니다. 왜 @Transactional처럼 메소드에 주석을다는 것이 불가능합니까?

다음은 스택 추적입니다.

Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at my.project.App.main(App.java:13)
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:98)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:75)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:378)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:155)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 7 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.auth.WaffleAuthenticationWrapperFilter my.project.config.WebSecurityConfig.waffleAuthenticationWrapperFilter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.boot.context.embedded.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:209)
    at org.springframework.boot.context.embedded.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:165)
    at org.springframework.boot.context.embedded.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:160)
    at org.springframework.boot.context.embedded.ServletContextInitializerBeans.addAdaptableBeans(ServletContextInitializerBeans.java:143)
    at org.springframework.boot.context.embedded.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:74)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getServletContextInitializerBeans(EmbeddedWebApplicationContext.java:234)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:221)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:54)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5151)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.auth.WaffleAuthenticationWrapperFilter my.project.config.WebSecurityConfig.waffleAuthenticationWrapperFilter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:649)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 35 more
Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.auth.WaffleAuthenticationWrapperFilter my.project.config.WebSecurityConfig.waffleAuthenticationWrapperFilter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:164)
    at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1365)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:606)
    ... 37 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.auth.WaffleAuthenticationWrapperFilter my.project.config.WebSecurityConfig.waffleAuthenticationWrapperFilter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:523)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:512)
    at org.springframework.security.config.annotation.web.configuration.AutowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers(AutowiredWebSecurityConfigurersIgnoreParents.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:112)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:129)
    at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:49)
    at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:342)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
    ... 41 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.auth.WaffleAuthenticationWrapperFilter my.project.config.WebSecurityConfig.waffleAuthenticationWrapperFilter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 63 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'waffleAuthenticationWrapperFilter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 65 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.project.services.UserService my.project.auth.WaffleAuthenticationWrapperFilter.userService; nested exception is java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 76 more
Caused by: java.lang.IllegalArgumentException: Can not set my.project.services.UserService field my.project.auth.WaffleAuthenticationWrapperFilter.userService to com.sun.proxy.$Proxy84
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
    at java.lang.reflect.Field.set(Unknown Source)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:557)
    ... 78 more

해결법

  1. ==============================

    1.AOP 스프링을 사용하려면 프록시는 2 가지의 JDK 동적 프록시 (인터페이스 기반)와 CgLIB 기반 프록시 (클래스 기반)를 사용합니다. 기본적으로 Spring은 하나 이상의 인터페이스를 구현하는 클래스에 JDK 동적 프록시를 사용합니다.

    AOP 스프링을 사용하려면 프록시는 2 가지의 JDK 동적 프록시 (인터페이스 기반)와 CgLIB 기반 프록시 (클래스 기반)를 사용합니다. 기본적으로 Spring은 하나 이상의 인터페이스를 구현하는 클래스에 JDK 동적 프록시를 사용합니다.

    런타임시 래핑하는 클래스 (UserService)의 모든 인터페이스 (UserDetailsService)를 구현하는 동적으로 생성 된 객체 (프록시)를 가져옵니다. 그래서 동적으로 생성 된 객체는 UserDetailsService이지만 UserService는 아닙니다.

    따라서 프록시를 UserService로 캐스팅 할 수 없다는 오류가 발생합니다.

    이 문제를 해결하는 방법은 적어도 두 가지가 있습니다.

    getUserByUsername을 호출 할 때 새로운 인터페이스를 생성하고이를 UserDetailsService와 함께 구현해야합니다.

    public interface UserService {
        User getUserByUsername(String username);
        void storeUser(User user);
        List<User> findAllUsers();
    }
    
    @Service("userService")
    public class UserServiceImpl implements UserDetailsService, UserService { ... }
    

    이렇게하면 UserService가 이제 인터페이스가되어 필터를 그대로 둡니다. 인터페이스에 다른 이름을 지정하면 필터의 UserService 필드를 해당 유형으로 변경해야합니다.

    클래스 기반 프록시를 사용하는 스프링 부팅을 사용하는 경우 application.properties 파일에 속성을 추가하는 것만 큼 쉽습니다.

    spring.aop.proxy-target-class=true
    

    이렇게하면 클래스 기반 프록시가 만들어 지므로 필터에 대한 코드를 변경하지 않고 그대로 둘 수 있습니다.

  2. ==============================

    2.

    @Autowired
    private UserService userService;
    

    해야한다

    @Autowired
    private UserDetailsService  userService;
    

    @Transactional 프록시는 UserService의 인스턴스가 아니기 때문에 UserDetailService (사용자 인터페이스)의 인스턴스입니다.

  3. ==============================

    3.@mdeinum이 지적했듯이 java의 네이티브 프록시는 클래스가 아닌 프록시 인터페이스 만 할 수 있습니다. 이것은 모범 사례입니다. 그래서 당신은해야 할 것입니다 :

    @mdeinum이 지적했듯이 java의 네이티브 프록시는 클래스가 아닌 프록시 인터페이스 만 할 수 있습니다. 이것은 모범 사례입니다. 그래서 당신은해야 할 것입니다 :

    @Autowired
    private IUserService userService;
    

    그리고

    public class UserService implements IUserService
    

    그러나, 가능하지 않은 경우 (특히 AOP 사용)가 있습니다. 그렇다면 기본 Java 프록시 대신 cglib 프록시를 사용할 수 있습니다. 이것을 (Maven?) 의존성에 추가해야합니다 :

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>${cglib.version}</version>
        </dependency>
    

    그리고 spring-aop에 프록시 클래스를 알리십시오.

    <aop:aspectj-autoproxy proxy-target-class="true"/>
    
  4. from https://stackoverflow.com/questions/30344084/why-can-a-class-with-a-transactional-method-not-be-autowired by cc-by-sa and MIT license