COnfiguration属性注释问题

时间:2015-12-10 16:43:44

标签: java spring spring-boot spring-cloud spring-properties

我有一个Git配置和spring服务器指向该配置。然后我创建了一个具有以下配置的客户端..以及要在Properties对象中填充的预期属性。有些原因它不能使用Spring云配置。但它确实可以与application.yml或application.properties一起使用。我可以看到条形图正确填充..但不是属性。

任何想法?

@SpringBootApplication
@EnableAutoConfiguration
@RestController
@RefreshScope
@ComponentScan
@EnableConfigurationProperties
@ConfigurationProperties(prefix="datasource.mysql.jpa")

public class ConfigClientApplication {

    private Properties properties;

    public Properties getProperties() {
        return properties;
    }

    @Value("${datasource.mysql.jpa.hibernate.dialect:sss}")
    private String bar;
    @RequestMapping("/")
    public String home() {
        String a ="";
        try {
            a = (String)properties.get("datasource.mysql.jpa.hibernate.dialect");
        }catch (Exception e){
            a = e.getMessage();
        }
        return "Hello "+bar + a;
    }

1 个答案:

答案 0 :(得分:1)

不要以这种方式将@Value注释与@ConfigurationProperties结合使用。我很幸运将属性组映射到内部类,如下所示:

test1.property1=...
test1.test2.property2=...
test1.test2.property3=...

将映射为:

import javax.validation.constraints.NotNull;

import lombok.Getter;
import lombok.Setter;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(locations = "classpath:myapp.properties")
public class ApplicationProperties {

    private String property1;
    private Test2 test2;

    @Getter
    @Setter
    @ConfigurationProperties(prefix = "test2")
    public static class Test2 {
        @NotNull
        private String property2;
        @NotNull
        private String property3;
    }
}