简体   繁体   中英

Default field value in spring boot application properties

Recently I started working with Pageable in my Spring Boot application. After doing some digging I found out that you can set the default page size in the application.properties like this:

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

Can we do this with normal classes as well? So lets say I have a class Page in the package:

com.myproject.entities and thid class has a field called size

could i do something similar? Or is there anyway to achieve this?

Thank you in advance for all the answers.

You can set this property value initially and make two different constructors this way:

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;
  }
  
}

This way the correct constructor will be called depending on the arguments provided and inside the constructor you take the argument you got or you use the default property value.

You could follows the way Spring did

  1. Define configuration properties for your configuration/service ( spring code )

@ConfigurationProperties("spring.data.web") public 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;
    }
}

}

  1. Define properties in your application.properties:

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

    or spring.data.web.pageable.defaultPageSize: 40

  2. Enable those properties in your configuration/service ( spring code )

    @Configuration

    @EnableConfigurationProperties(SpringDataWebProperties.class)

    public 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())); }; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM