初始化时在Spring Bean中使用@Value

smtd7mpg  于 2023-02-03  发布在  Spring
关注(0)|答案(3)|浏览(190)

我需要从www.example.com文件提供超时application.properties,但在初始化时失败,因为属性尚未加载。加载属性的最佳实践是什么?

@Configuration
@AllArgsConstructor
@Slf4j
public class Config {

    @Value("${connectionTimeout}") 
    int connectionTimeout;
    @Value("${responseTimeout}") 
    int responseTimeout;

    @Bean
    public ClientHttpConnector getConnector() {
        HttpClient client = HttpClient.create();

        client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout)
                .responseTimeout(Duration.ofMillis(responseTimeout));

        return new ReactorClientHttpConnector(client);

    }
    @Bean
    public WebClient webClient() {
        return WebClient.builder().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .clientConnector(getConnector())
                .build();
    }

application.properties 文件夹中的www.example.com

connectionTimeout=30000
responseTimeout=30000

就像其他类似的帖子中建议的那样,我尝试使用@ConfigurationProperties,但是根本不起作用。有没有一些我不知道的更简单的方法来加载它们?

icomxhvb

icomxhvb1#

尝试通过构造函数注入值:

public Config(@Value("${connectionTimeout}") int connectionTimeout,
              @Value("${responseTimeout}") int responseTimeout) {
    // assign to fields
}
ippsafx7

ippsafx72#

尝试使用Environment类。

@Configuration
public class Config {

   private final Environment environment;

   @Autowired
   public Config(Environment environment) {
       this.environment = environment;
   }

   @Bean
   public SimpleBean simpleBean() {
       SimpleBean simpleBean = new SimpleBean();
       simpleBean.setConfOne(environment.getProperty("conf.one"));
       simpleBean.setConfTwo(environment.getProperty("conf.two"));
       return simpleBean;
   } 
}
2vuwiymt

2vuwiymt3#

你得到的错误

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'getConnector' defined in ...config.Config: 
Unsatisfied dependency expressed through method 'getConnector' parameter 0;
nested exception is org.springframework.beans.TypeMismatchException:
 Failed to convert value of type 'java.lang.String' to required type 'int';
 nested exception is java.lang.NumberFormatException: For input string: 
"${connectionTimeout}"  <-----

表示它试图将"${connectionTimeout}"作为一个值读取。

connectionTimeout=${connectionTimeout}

在您application.properties
我的直觉是问题来自

@Value("${connectionTimeout}") 
    int connectionTimeout;
    @Value("${responseTimeout}") 
    int responseTimeout;

希望对你的调试有所帮助

相关问题