Spring Boot:如何使用ConfigurationProperties获取程序参数

时间:2017-01-19 01:52:41

标签: java spring spring-boot

我在启动应用时尝试从命令行获取一些属性。我真的尝试了很多解决方案但是没有效果。我只会使用 @Value 作为最后的解决方案

java -jar myjar.jar --test.property=something

这里有一些课程

  

主要课程

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(TestApplication.class);
        builder.run(args);
    }
}
  

配置类

@Configuration
@EnableConfigurationProperties(StringProperties.class)
public class StringConfiguration {

    @Autowired
    private StringProperties stringProperties;

    @Bean(name = "customBeanName")
    public List<String> properties() {
        List<String> properties = new ArrayList<>();

        properties.add(stringProperties.getString());

        return properties;
    }
}
  

属性类

@Component
@ConfigurationProperties("test")
public class StringProperties {

    private String property;

    public String getString() {
        return property;
    }
}

1 个答案:

答案 0 :(得分:4)

Ops .....我已经测试了你的代码。它是在StringProperties中错过的setProperty。

 public void setProperty(String property) {
        this.property = property;
    }