在用@ConfigurationProperties定义属性时,我可以定义特定字段的前缀而不是整个类吗?
例如,假设我们有一个Properties类
@ConfigurationProperties(prefix = "com.example")
public class MyProperties {
private String host;
private String port;
// Geters and setters...
}这将将字段host和port绑定到com.example.host和com.example.port。假设我想将port绑定到com.example.something.port。这样做的方法是定义一个内部类Something并在那里添加属性port。但如果我需要更多的前缀,它将变得太麻烦。我试图在setter上添加@ConfigurationProperties,因为注释的目标是ElementType.TYPE和ElementType.METHOD:
@ConfigurationProperties(prefix = "com.example.something.port")
public void setPort(int port) {...}但到头来还是行不通的。除了内部类之外,还有其他方法来自定义前缀吗?
发布于 2015-12-10 20:04:54
@Value注释即可。您可以使用
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;
}
}https://stackoverflow.com/questions/34207920
复制相似问题