Reputation: 320
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;
}
}
Upvotes: 3
Views: 390
Reputation: 13581
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
Upvotes: 4