Spring boot実用的かつ冷門的な注釈
一、コメント
この号は先に注釈の統計をして、私に会ったら文章の最後のappedです。
1.@ConfigrationPropties(「xxx」)
通常は@Value()を使ってプロファイルのパラメータを注入しますが、構成パラメータが非常に複雑で、階層が深いと太って見えます。この時、この注釈は役に立ちます。例えば、私達の配置ファイル:
この号は先に注釈の統計をして、私に会ったら文章の最後のappedです。
1.@ConfigrationPropties(「xxx」)
通常は@Value()を使ってプロファイルのパラメータを注入しますが、構成パラメータが非常に複雑で、階層が深いと太って見えます。この時、この注釈は役に立ちます。例えば、私達の配置ファイル:
acme.enabled=false;
acme.remote-address=192.168.1.10;
acme.security.username=BBSee;
acme.security.password=123*_678;
acme.security.roles= ;
私たちは次のように注入できます。 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 roles = new ArrayList<>(Collections.singleton("USER"));
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
public List getRoles() { ... }
public void setRoles(List roles) { ... }
}
}
yml:my:
servers:
- dev.bbsee.com
- another.bbsee.com
@ConfigurationProperties(prefix="my")
public class Config {
private List servers = new ArrayList();
public List getServers() {
return this.servers;
}
}
そして、beanとして使えます。@Service
public class MyService {
private final AcmeProperties properties;
@Autowired
public MyService(AcmeProperties properties) {
this.properties = properties;
}
//...
@PostConstruct
public void openConnection() {
Server server = new Server(this.properties.getRemoteAddress());
// ...
}
}
この注釈の下にはフォーマット変換、パラメータ有効性チェックなどの機能があります。