Home > Software engineering >  @Value not working, field comes null ever
@Value not working, field comes null ever

Time:01-21

image from class and properties

Hi devs, I am tryng catch values in aplication.properties but value comes null ever,i already changed anotation to @component, changed name, changed envrioment but the field ever comes null. Can you help me ?

I don't know if it makes a difference but I'm using gradle.

class catch values


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Data
public class TokenUtils {
@Value("${jwt.secret}")
public String expiration;

    @Value("${jwt.expiration}")
    public String secret;
    
    public String createToken(String email) {
        Date expirationDate = new Date(System.currentTimeMillis()   expiration);
    
        Map<String, Object> extra = new HashMap<>();
    
        return Jwts.builder()
                .setSubject(email)
                .setExpiration(expirationDate)
                .signWith(Keys.hmacShaKeyFor(secret.getBytes()), SignatureAlgorithm.ES256)
                .compact();
    }
    
    public UsernamePasswordAuthenticationToken getAuthetication(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(Keys.hmacShaKeyFor(secret.getBytes()))
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
    
            String email = claims.getSubject();
            return new UsernamePasswordAuthenticationToken(email, null, Collections.emptyList());
        } catch (JwtException e) {
            throw e;
        }
    }

}

application.properties

spring.profiles.active=test
jwt.secret=ewqertqwtqwetqwt
jwt.expiration=604800000

CodePudding user response:

In the code, instances of TokenUtils are manually created by calling new ... here and here. This will circumvent the bean container completely, i.e. features like @Value will not take effect. Instead of creating new instances, we should inject an instance of TokenUtils into those classes, e.g.:

@Component
public class JWTauthorizationFilter extends OncePerRequestFilter {
    private final TokenUtils tokenUtils;

    public JWTauthorizationFilter(TokenUtils tokenUtils) {
        this.tokenUtils = tokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.replace("Bearer ", "");
            UsernamePasswordAuthenticationToken authenticationToken = tokenUtils.getAuthetication(token);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
  • Related