微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Boot应用程序属性中的默认字段值

如何解决Spring Boot应用程序属性中的默认字段值

最近,我开始在Spring Boot应用程序中使用Pageable。经过一番挖掘,我发现您可以像这样在application.properties中设置页面大小:

spring.data.web.pageable.default-page-size: 40

我们也可以使用普通类吗?所以可以说我在包中有一个Page

com.myproject.entities和thid类有一个名为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;
  }
  
}

这样,将根据所提供的参数来调用正确的构造函数,并且在构造函数中,您可以使用获得的参数或使用默认属性值。

,

您可以遵循Spring的方式

  1. 为您的配置/服务(spring code)定义配置属性

@ConfigurationProperties(“ spring.data.web”) 公共类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;
    }
}

}

  1. 在您的application.properties中定义属性:

    spring.data.web.pageable.default-page-size: 40

    spring.data.web.pageable.defaultPageSize: 40

  2. 在配置/服务(spring code)中启用这些属性

    @配置

    @EnableConfigurationProperties(SpringDataWebProperties.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()));
        };
    }
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。