@Value 未从 application.properties 中选取

问题描述 投票:0回答:1

具有以下 JWTTokenService 类:

package com.project.blogapi.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;

import static java.lang.System.*;

@Service
public class JWTTokenService implements TokenService {

    private final Algorithm algorithm;
    private final String SIGNING_KEY;
    private final long TOKEN_EXPIRY_MILLIS = (1000 * 60 * 60 * 24);
    private final String ISSUER = "blog-api";
    public JWTTokenService(String signingKey) {
        SIGNING_KEY = signingKey;
        this.algorithm = Algorithm.HMAC256(SIGNING_KEY);
    }

    @Override
    public String createAuthToken(String username) {
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(new java.util.Date())
                .withExpiresAt(new java.util.Date(System.currentTimeMillis() + TOKEN_EXPIRY_MILLIS))
                .withSubject(username)
                .sign(algorithm);
        return token;
    }

    @Override
    public String getUsernameFromToken(String token) throws IllegalStateException {
        var verifier = JWT.require(algorithm)
                .withIssuer(ISSUER)
                .build();

        var decodedToken = verifier.verify(token);
        return decodedToken.getSubject();
    }
}

有一个TokeService接口:

package com.project.blogapi.security;

public interface TokenService {
    /*
        create a JWT or Service side token for given username
     */
    String createAuthToken(String username);
    String getUsernameFromToken(String token) throws IllegalStateException;

}

和 JWTTokenProperties 来创建 JWTTokenService,其值最好来自 application.properties

package com.project.blogapi.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JWTTokenProperties {

    public static @Value("${key}") String SIGNING_KEY;

    public static JWTTokenService create(){
        return new JWTTokenService(SIGNING_KEY);
    }
}

尝试了不同的方法,但 SIGNING_KEY 始终为空

直接使用 jwttokenservices 尝试不使用 tokenproperties。没用。

spring spring-boot spring-data-jpa application.properties
1个回答
0
投票

像这样删除静态修饰符

public @Value("${key}") String SIGNING_KEY;
© www.soinside.com 2019 - 2024. All rights reserved.