【问题标题】:Not Able to use @value inside @bean in Spring boot [duplicate]在 Spring Boot 中无法在 @bean 中使用 @value [重复]
【发布时间】:2020-08-25 18:22:42
【问题描述】:

大家好,我用的是spring 2.4版本和spring cloud的feign cloud

但是当我从属性文件中读取时,我无法在 @bean 方法中使用一些常量值

@Configuration
public class FeignClientConfiguration {

    @Value("${app.basic.auth.username}")
    private static String userName;

    @Value("${app.basic.auth.password}")
    private static String password;


    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        // return new BasicAuthRequestInterceptor("admin", "admin");
        return new BasicAuthRequestInterceptor(userName, password);
    }
}

但我虽然提供了这样的价值,但我会很好地工作

return new BasicAuthRequestInterceptor("admin", "admin");

我不知道为什么这不起作用,你能建议我任何方法来实现这一点

【问题讨论】:

  • 试试public BasicAuthRequestInterceptor basicAuthRequestInterceptor(@Value("${...}") String username, ....) {
  • 这能回答你的问题吗? Spring: How to inject a value to static field?
  • 我也尝试过,但不起作用
  • @ErvinSzilagyi 我也试过了,但没用
  • 检查您的配置文件以确保它是正确的。另外,由于FeignClientConfiguration 是单身人士,成员是private,我看不出他们为什么应该是staticnon-final

标签: java spring spring-boot spring-security spring-cloud-feign


【解决方案1】:

您应该将配置类和 basicAuthRequestInterceptor 方法分开。

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "app")    
public class LoginProperties {

    private String username;
    private String password;    
}

在您的属性文件中,具有以下内容:

app.username = user
app.password = 123

然后在您的控制器/服务类中,执行以下操作。

@Autowired
private LoginProperties loginProperties; 

public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(loginProperties.getUserName(), loginProperties.password());
    }

【讨论】:

    【解决方案2】:

    找出答案的最佳方法是创建一个简单的 @PostConstruct 方法并打印这两个值。如果它们是 null,则意味着 spring 无法解析这些属性值。

    确保您已使用 PropertyPlaceholderConfigurer 初始化属性并且属性文件的路径正确(即使相对于类路径)。

    密切关注日志,不要忽略任何异常。

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 2019-04-18
      • 2018-05-23
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多