简体   繁体   English

Java spring @Value注释

[英]Java spring @Value annotation

I have a Spring Boot application with a class TokenProvider where i get some token from application.properties. 我有一个带有TokenProvider类的Spring Boot应用程序,我从application.properties获取一些令牌。 In another controller class TestController i need to create a object new TokenProvider and retrieve the value. 在另一个控制器类TestController中,我需要创建一个对象new TokenProvider并检索该值。 It gives me null values. 它给了我空值。 Why it doesn't work ? 为什么它不起作用?

PS: If i inject TokenProvider in TestController (with @Autowired JwtTokenProvider tokenProvider; )it works. PS:如果我在TestController中注入TokenProvider(使用@Autowired JwtTokenProvider tokenProvider;)它可以工作。

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;
    }
}

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. 在使用new创建JwtTokenProvider情况下,它不是由Spring创建的,并且所有注释(如@Value基本上都被忽略 - 这就是Spring的工作方式。 What you can do is to create the JwtTokenProvider in proper Java @Configuration class providing @Value String token parameter 你可以做的是在适当的Java @Configuration类中创建JwtTokenProvider ,提供@Value String token参数

@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 但仍然 - 你需要使用Spring依赖注入机制来让@Value工作

See https://baledung.com/spring-value-annotation 请参阅https://baledung.com/spring-value-annotation

You can use the @Value annotation to inject values into fields in beans that Spring manages. 您可以使用@Value批注将值注入Spring管理的bean中的字段。

If your bean is not @Autowired, Spring can't inject the value. 如果您的bean不是@Autowired,则Spring无法注入该值。

In case you don't want to use the @Value annotation, you can always use the Java Properties class (with .getProperty method) to retrieve your value. 如果您不想使用@Value批注,则始终可以使用Java Properties类(使用.getProperty方法)来检索您的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM