Home > Net >  TransactionInterceptor doesn't intercept @Transactional method
TransactionInterceptor doesn't intercept @Transactional method

Time:11-21

I made @Transactional method in @Service class. Then, TransactionInterceptor doesn't intercept @Transaction method.
But when I make @Transactional method in @Controller class for test, then TransactionInterceptor intercept this method.
I want TransactionInterceptor intercept @Transactional method of @Service class.
How should I do?

Following code is my Service class. This code is be invoked by @Controller class.

@Service
public class TokenProvider implements InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(TokenProvider.class);

    private static final String AUTHORITIES_KEY = "auth"; // JWT Claim Key

    @Value("${jwt.secret}")
    private String secret; // private secret key
    @Value("${jwt.token-validity-in-seconds}")
    private long tokenValidityInMilliseconds; 
    private Key key;

    private final RefreshTokenRepository refreshTokenRepository;
    private final UserRepository userRepository;

    public TokenProvider(
            UserRepository userRepository,
            RefreshTokenRepository refreshTokenRepository) {
        this.userRepository = userRepository;
        this.refreshTokenRepository = refreshTokenRepository;
    }

    //...

    @Transactional
    protected HttpHeaders _updateRefreshTokenAndGetHeader(String refreshToken, String accessToken, String newAccessToken) throws Exception {
        RefreshToken token = refreshTokenRepository.findByRefreshTokenAndAccessToken(refreshToken, accessToken)
                .orElseThrow(NullPointerException::new);
        if (!token.isValid()) {
            throw new Exception("token is not valid.");
        }
        String name = TransactionSynchronizationManager.getCurrentTransactionName(); //null
        boolean transactional = TransactionSynchronizationManager.isActualTransactionActive(); //false

        String updatedToken = updateRefreshToken(token, newAccessToken);
        return getHeaderForRefreshToken(updatedToken);
    }

    //...
}

CodePudding user response:

Problem description as method visibility point to that issue/note:

(i)Note: Method visibility and @Transactional

When you use transactional proxies with Spring’s standard configuration, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private, or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. If you need to annotate non-public methods, consider the tip in the following paragraph for class-based proxies or consider using AspectJ compile-time or load-time weaving (described later).

From: https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative-annotations

  • Related