3

I have a Spring Boot application with a class TokenProvider where i get some token from application.properties. In another controller class TestController i need to create a object new TokenProvider and retrieve the value. It gives me null values. Why it doesn't work ?

PS: If i inject TokenProvider in TestController (with @Autowired JwtTokenProvider tokenProvider; )it works.

Why i cannot retrieve token without injecting ?

@Component
public class JwtTokenProvider {
    private static Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);

    @Value("${app.jwtSecret}")
    private String jwtSecret;

    public String getJwtSecret() {
        return jwtSecret;
    }

}

@RestController
@RequestMapping("/test")
public class TestController {

//    @Autowired
//    JwtTokenProvider tokenProvider;

    @RequestMapping(value = "/get_propertie")
    public String getPropertie() {
        JwtTokenProvider jwt = new JwtTokenProvider();
        String res = "jwt" + jwt.getJwtSecret();
        return res;
    }
}

1 Answer 1

4

in case of creating JwtTokenProvider with new it is not being created by Spring and all annotations like @Value are basically being ignored - that's how Spring is working. What you can do is to create the JwtTokenProvider in proper Java @Configuration class providing @Value String token parameter

@Configuration
public class TokenConfig {
    @Bean
    public JwtTokenProvider jwtTokenProvider(@Value("${app.jwtSecret}") token) {
        return new JwtTokenProvider(token); // or some setter depends on what the class provide
    }
}

but still - you need to use on of Spring dependency injection mechanism to have @Value working

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.