[英]Default field value in spring boot application properties
最近我開始在我的 Spring Boot 應用程序中使用Pageable
。 在做了一些挖掘之后,我發現你可以在application.properties
中設置默認頁面大小,如下所示:
spring.data.web.pageable.default-page-size: 40
我們也可以在普通課程上這樣做嗎? 所以假設我在 package 中有一個 class Page
:
com.myproject.entities
和 thid class 有一個名為size
的字段
我可以做類似的事情嗎? 還是有辦法實現這一目標?
預先感謝您提供所有答案。
您可以最初設置此屬性值並以這種方式創建兩個不同的構造函數:
class Solution {
public static void main(String[] args) {
Page p1 = new Page("black");
Page p2 = new Page("white", 5);
System.out.println(p1.getSize()); //prints 1
System.out.println(p2.getSize()); //prints 5
}
}
class Page {
int size = 1;
String color;
public Page(String color) {
this.color = color;
}
public Page(String color, int size) {
this.color = color;
this.size = size;
}
int getSize() {
return this.size;
}
}
這樣,將根據提供的 arguments 調用正確的構造函數,並在構造函數內部使用您獲得的參數或使用默認屬性值。
您可以按照 Spring 的方式進行操作
@ConfigurationProperties("spring.data.web") 公共 class SpringDataWebProperties {
private final Pageable pageable = new Pageable();
public Pageable getPageable() {
return this.pageable;
}
/**
* Pageable properties.
*/
public static class Pageable {
private int defaultPageSize = 20;
public int getDefaultPageSize() {
return this.defaultPageSize;
}
public void setDefaultPageSize(int defaultPageSize) {
this.defaultPageSize = defaultPageSize;
}
}
}
在您的 application.properties 中定義屬性:
spring.data.web.pageable.default-page-size: 40
或spring.data.web.pageable.defaultPageSize: 40
在您的配置/服務中啟用這些屬性( spring 代碼)
@配置
@EnableConfigurationProperties(SpringDataWebProperties.class)
公共 class SpringDataWebAutoConfiguration {
private final SpringDataWebProperties properties; public SpringDataWebAutoConfiguration(SpringDataWebProperties properties) { this.properties = properties; } @Bean public PageableHandlerMethodArgumentResolverCustomizer pageableCustomizer() { return (resolver) -> { Pageable pageable = this.properties.getPageable(); resolver.setFallbackPageable(PageRequest.of(0, pageable.getDefaultPageSize())); }; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.