Springブート@ConfigurationPropertiesの例
イメージ://wp-content/uploads/2017/01/spring-boot-configurationproperties.png[spring-boot-configurationproperties]
Spring Boot `@ ConfigurationProperties`は、開発者がファイル全体をオブジェクトに簡単にマップできるようにします。
1.シンプルプロパティファイル
通常、
@ Value`アノテーションを使用して
.properties`値を1つずつ挿入します。これは、小さく単純な構造の `.properties`ファイルに適しています。
global.properties
[email protected] thread-pool=12
1.1 `@ Value`の例です。
GlobalProperties.java
@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {
@Value("${thread-pool}")
private int threadPool;
@Value("${email}")
private String email;
//getters and setters
}
1.2 `@ConfigurationProperties`の例です。
GlobalProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
@Component
@PropertySource("classpath:global.properties")
@ConfigurationProperties
public class GlobalProperties {
private int threadPool;
private String email;
//getters and setters
}
2.複合プロパティファイル
2.1複雑な構造の
.properties`ファイルを見直して、
@ Value`アノテーションを使ってどのように値をマップするのですか?
application.properties
#Logging logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG #Global [email protected] thread-pool=10 #App app.menus[0].title=Home app.menus[0].name=Home app.menus[0].path=/app.menus[1].title=Login app.menus[1].name=Login app.menus[1].path=/login app.compiler.timeout=5 app.compiler.output-folder=/temp/ app.error=/error/.... またはYAMLの平等である。 application.yml
logging:
level:
org.springframework.web: ERROR
com.mkyong: DEBUG
email:
[email protected]
thread-pool: 10
app:
menus:
– title: Home
name: Home
path:/ – title: Login
name: Login
path:/login
compiler:
timeout: 5
output-folder:/temp/ error:/error/….
2.2
@ConfigurationProperties`がレスキューするようになり、次のように
@ConfigurationProperties`を作成します:
AppProperties.java
package com.mkyong;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConfigurationProperties("app")//prefix app, find app.** values
public class AppProperties {
private String error;
private List<Menu> menus = new ArrayList<>();
private Compiler compiler = new Compiler();
public static class Menu {
private String name;
private String path;
private String title;
//getters and setters
@Override
public String toString() {
return "Menu{" +
"name='" + name + '\'' +
", path='" + path + '\'' +
", title='" + title + '\'' +
'}';
}
}
public static class Compiler {
private String timeout;
private String outputFolder;
//getters and setters
@Override
public String toString() {
return "Compiler{" +
"timeout='" + timeout + '\'' +
", outputFolder='" + outputFolder + '\'' +
'}';
}
}
//getters and setters
}
GlobalProperties.java
package com.mkyong;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties//no prefix, find root level values.
public class GlobalProperties {
private int threadPool;
private String email;
//getters and setters
}
デモ
3.1 .properties値がオブジェクトに正しくマップされていることを確認するためのテスト。
WelcomeController.java
package com.mkyong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class WelcomeController {
private static final Logger logger = LoggerFactory.getLogger(WelcomeController.class);
private AppProperties app;
private GlobalProperties global;
@Autowired
public void setApp(AppProperties app) {
this.app = app;
}
@Autowired
public void setGlobal(GlobalProperties global) {
this.global = global;
}
@RequestMapping("/")
public String welcome(Map<String, Object> model) {
String appProperties = app.toString();
String globalProperties = global.toString();
logger.debug("Welcome {}, {}", app, global);
model.put("message", appProperties + globalProperties);
return "welcome";
}
}
SpringBootWebApplication.java
package com.mkyong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[]args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
3.1 `mvn spring-boot:run`でSpring起動を開始し、デフォルトの/controllerにアクセスし、コンソールを見直してください:
コンソール
Welcome
AppProperties{error='/error/',
menus=[ Menu{name='Home', path='/', title='Home'},
Menu{name='Login', path='/login', title='Login'}
],
compiler=Compiler{timeout='5', outputFolder='/temp/'}},
GlobalProperties{threadPool=10, email='[email protected]'}
4. @ConfigurationProperties検証
4.1この
@ ConfigurationProperties`は、JSR-303 beanの検証をサポートしています - javax.validation
GlobalProperties.java
package com.mkyong;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@Component
@ConfigurationProperties
public class GlobalProperties {
@Max(5)
@Min(0)
private int threadPool;
@NotEmpty
private String email;
//getters and setters
}
4.2 Spring起動を再試行し、コンソールを確認してください:
コンソール
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
アプリケーションが開始に失敗しました
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
説明:
ターゲットGlobalProperties {threadPool = 10、email='[email protected] '}へのバインドに失敗しました:
プロパティ:target.threadPool
値:10
理由:5以下でなければならない
アクション:
アプリケーションの設定を更新する
//...
-
注** +詳細については、公式のhttps://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Spring Boot Externalized Configuration]を参照してください。
ソースコードをダウンロードする
ダウンロードする –
spring-boot-properties.zip
(15 KB)
参考文献
ブート – 外部化構成]。リンク://spring/spring-propertysources-example/[Spring @PropertySource
bean検証
リンク://tag/jsr303/[jsr303]
properties
spring boot
yaml