springboot2.2.6.RELEASE chapter1
2020-04-04 本文已影响0人
淼哥1986
使用@Value(${property})注释注入配置属性有时很麻烦,特别是当您使用多个属性时。SpringBoot提供了一种处理属性的替代方法:
package com.example;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("acme")
public class AcmeProperties {
private boolean enabled;
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
public List<String> getRoles() { ... }
public void setRoles(List<String> roles) { ... }
}
}
acme.enabled, with a value of false by default.
• acme.remote-address, with a type that can be coerced from String.
• acme.security.username, with a nested "security" object whose name is determined by the name
of the property. In particular, the return type is not used at all there and could have been
SecurityProperties.
• acme.security.password.
• acme.security.roles, with a collection of String that defaults to USER.