Ame*_* A. 5 java properties spring-boot
使用定义属性时@ConfigurationProperties,可以定义特定字段的前缀而不是整个类吗?
例如,假设我们有一个Properties类
@ConfigurationProperties(prefix = "com.example")
public class MyProperties {
private String host;
private String port;
// Geters and setters...
}
Run Code Online (Sandbox Code Playgroud)
这会将字段host和绑定port到com.example.host和com.example.port。假设我要绑定port到com.example.something.port。完成此操作的方法是定义一个Inner类Something并在其中添加属性port。但是,如果我需要更多的前缀,它将变得很麻烦。我尝试添加@ConfigurationProperties设置器,因为注释的目标是ElementType.TYPE和ElementType.METHOD:
@ConfigurationProperties(prefix = "com.example.something.port")
public void setPort(int port) {...}
Run Code Online (Sandbox Code Playgroud)
但这最终没有用。除了通过内部类之外,还有另一种自定义前缀的方法吗?
如果你想映射单个属性,只需使用@Value注释即可。
如果您有团体,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3140 次 |
| 最近记录: |