Properties With Spring And Spring Boot Baeldungspring Boot Application

Kenji Sato
-
properties with spring and spring boot baeldungspring boot application

1. What are Spring Boot Properties? Spring Boot properties are configuration settings that control the behavior of your Spring Boot application. They allow you to externalize configuration and work with the same application code in different environments. Types of Properties: - Application Properties: Basic application configuration - Profile-specific Properties: Environment-specific configurations - Third-party Properties: Configuration for integrated libraries and frameworks 2. Why Use Properties and When?

Benefits: - Externalized Configuration: Separate configuration from code - Environment-specific Settings: Different configurations for dev, test, prod - No Code Changes: Modify behavior without recompiling - Type Safety: Strongly bound to configuration classes - Auto-completion: IDE support for property names When to Use: - Database connections - Server configuration - Feature toggles - External service URLs - Security settings - Logging levels - Performance tuning 3. Ways of Using Properties 3.1 Property Files Location (Order of Precedence) # 1. Dev tools global settings (.spring-boot-devtools.properties) # 2.

@TestPropertySource on tests # 3. @SpringBootTest properties # 4. Command line arguments # 5. SPRING_APPLICATION_JSON (inline JSON embedded in env variable) # 6. ServletConfig init parameters # 7. ServletContext init parameters # 8. java:comp/env JNDI attributes # 9. System.getProperties() # 10. OS environment variables # 11. RandomValuePropertySource (random.*) # 12. Profile-specific application-{profile}.properties # 13. Application properties (application.properties) # 14. @PropertySource on @Configuration classes # 15.

Default properties (SpringApplication.setDefaultProperties) 3.2 Property Files Format application.properties: # Basic properties server.port=8080 spring.application.name=myapp # Database spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=user spring.datasource.password=pass # Lists and arrays spring.profiles.active=dev,test myapp.servers[0]=server1 myapp.servers[1]=server2 application.yml: # YAML format (alternative) server: port: 8080 spring: application: name: myapp datasource: url: jdbc:mysql://localhost:3306/mydb username: user password: pass myapp: servers: - server1 - server2 3.3 Accessing Properties in Code Using @Value: @Component public class MyComponent { @Value("${server.port}") private int serverPort; @Value("${myapp.feature.enabled:false}") // default value private boolean featureEnabled; @Value("${myapp.servers}") private List<String> servers; } Using @ConfigurationProperties: @Configuration @ConfigurationProperties(prefix = "app.config") public class AppConfig { private String name; private List<String> servers = new ArrayList<>(); private Database database = new Database(); // getters and setters public static class Database { private String host; private int port; // getters and setters } } application.properties: app.config.name=MyApplication app.config.servers[0]=server1 app.config.servers[1]=server2 app.config.database.host=localhost app.config.database.port=3306 3.4 Profile-specific Properties application-dev.properties: spring.datasource.url=jdbc:h2:mem:testdb spring.h2.console.enabled=true logging.level.com.myapp=DEBUG application-prod.properties: spring.datasource.url=jdbc:mysql://prod-db:3306/mydb logging.level.com.myapp=INFO management.endpoints.web.exposure.include=health,info 3.5 Conditional Configuration @Configuration @ConditionalOnProperty(name = "app.feature.cache.enabled", havingValue = "true") public class CacheConfig { // This configuration only loads if property is set to true } 4.

Common Properties by Category 4.1 Core Spring Properties # Application basic config spring.application.name=my-service spring.profiles.active=dev spring.main.banner-mode=console spring.main.lazy-initialization=true # Internationalization spring.messages.basename=messages spring.web.locale=en_US # File upload spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB 4.2 Database Properties (JDBC) # DataSource spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Connection pool (HikariCP) spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 # Embedded database spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true 4.3 JPA/Hibernate Properties # JPA spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.open-in-view=false # Hibernate specific spring.jpa.properties.hibernate.jdbc.batch_size=20 spring.jpa.properties.hibernate.order_inserts=true spring.jpa.properties.hibernate.order_updates=true spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true # Second-level cache spring.jpa.properties.hibernate.cache.use_second_level_cache=true spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory spring.jpa.properties.javax.persistence.sharedCache.mode=ALL 4.4 Web/Server Properties # Server configuration server.port=8080 server.servlet.context-path=/api server.servlet.session.timeout=30m server.compression.enabled=true server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json server.compression.min-response-size=1024 # Tomcat specific server.tomcat.max-threads=200 server.tomcat.max-connections=10000 server.tomcat.accept-count=100 server.tomcat.accesslog.enabled=true server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) # SSL server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=secret server.ssl.key-store-type=PKCS12 server.ssl.key-alias=tomcat 4.5 Security Properties # Basic Security spring.security.user.name=admin spring.security.user.password=secret spring.security.user.roles=ADMIN,USER # OAuth2 spring.security.oauth2.client.registration.my-client.client-id=client-id spring.security.oauth2.client.registration.my-client.client-secret=client-secret spring.security.oauth2.client.registration.my-client.scope=read,write spring.security.oauth2.client.registration.my-client.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.my-client.redirect-uri=http://localhost:8080/login/oauth2/code/my-client # JWT app.security.jwt.secret=mySecretKey app.security.jwt.expiration=86400000 4.6 Logging Properties # Logging levels logging.level.com.myapp=DEBUG logging.level.org.springframework.web=INFO logging.level.org.hibernate=WARN # Log file logging.file.name=app.log logging.file.path=/var/log logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n # Logback specific logging.logback.rollingpolicy.max-file-size=10MB logging.logback.rollingpolicy.max-history=30 4.7 Mail Properties # SMTP configuration spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=user@gmail.com spring.mail.password=app-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true # Mail sender spring.mail.default-encoding=UTF-8 spring.mail.protocol=smtp spring.mail.test-connection=false 4.8 Cache Properties # Cache auto-configuration spring.cache.type=redis spring.cache.redis.time-to-live=600000 spring.cache.redis.cache-null-values=true spring.cache.redis.key-prefix=cache: # Redis specific spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.database=0 spring.redis.timeout=2000 # Caffeine cache spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s 4.9 Actuator Properties # Actuator endpoints management.endpoints.web.exposure.include=health,info,metrics,env management.endpoints.web.exposure.exclude=shutdown management.endpoint.health.show-details=always management.endpoint.health.show-components=always # Health indicators management.health.db.enabled=true management.health.redis.enabled=true management.health.diskspace.enabled=true # Custom info management.info.env.enabled=true management.info.build.enabled=true management.info.git.enabled=true # Metrics management.metrics.export.prometheus.enabled=true management.metrics.distribution.percentiles-histogram.http.server.requests=true 4.10 Thymeleaf Properties # Thymeleaf template engine spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.cache=false # Set to true in production spring.thymeleaf.check-template-location=true 4.11 WebSocket Properties # WebSocket configuration spring.websocket.servlet.max-session-idle-timeout=300000 spring.websocket.servlet.max-text-message-buffer-size=8192 spring.websocket.servlet.max-binary-message-buffer-size=8192 # STOMP broker spring.websocket.stomp.relay.host=localhost spring.websocket.stomp.relay.port=61613 spring.websocket.stomp.broker.relay.enabled=true 4.12 Batch Properties # Spring Batch spring.batch.job.enabled=false spring.batch.job.name=myJob spring.batch.initialize-schema=always spring.batch.table-prefix=BATCH_ # Job repository spring.batch.jdbc.initialize-schema=always spring.batch.job.repository.isolation-level-for-create=default 4.13 Cloud Properties # Spring Cloud Config spring.cloud.config.uri=http://localhost:8888 spring.cloud.config.name=myapp spring.cloud.config.profile=dev spring.cloud.config.label=main # Eureka Client eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ eureka.instance.prefer-ip-address=true eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port} # Circuit Breaker resilience4j.circuitbreaker.instances.backend.failure-rate-threshold=50 resilience4j.circuitbreaker.instances.backend.wait-duration-in-open-state=10s 4.14 Compression Properties # Response compression server.compression.enabled=true server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml server.compression.min-response-size=1024 # Gzip compression for static content spring.resources.chain.gzipped=true spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/** 5.

Advanced Usage Examples 5.1 Custom Configuration Properties @Configuration @ConfigurationProperties(prefix = "app") @Validated public class AppProperties { @NotBlank private String name; @Min(1) private int maxConnections; private List<String> allowedHosts; private Security security = new Security(); // getters and setters public static class Security { private boolean enabled; private String secretKey; private long tokenValidity; // getters and setters } } 5.2 Profile-based Configuration @Configuration @Profile("dev") public class DevConfig { // Development specific beans } @Configuration @Profile("prod") public class ProdConfig { // Production specific beans } 5.3 Property Validation @ConfigurationProperties(prefix = "app") @Validated public class AppProperties { @NotNull @URL private String serverUrl; @Min(1) @Max(65535) private int serverPort; @Pattern(regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$") private String adminEmail; } 5.4 Dynamic Property Refresh @RefreshScope @Component public class MyRefreshedComponent { @Value("${app.dynamic.config}") private String dynamicConfig; // This value will be refreshed when /actuator/refresh is called } 6.

Best Practices - Use YAML for complex hierarchical configurations - Externalize environment-specific properties - Use sensible default values - Validate configuration properties - Use profile-specific properties for different environments - Keep sensitive data in secure property sources - Use @ConfigurationProperties for type-safe configuration - Document your custom properties Top comments (0)

People Also Asked

Properties with Spring and Spring Boot - BaeldungProperties and Configuration :: Spring BootProperties with Spring and Spring Boot - GeeksforGeeksHow to Access Values from application.properties in Spring ...Spring Boot Properties: Complete Tutorial - DEV CommunityCommon Application Properties :: Spring BootLearn Spring Boot Series - Baeldung?

1. What are Spring Boot Properties? Spring Boot properties are configuration settings that control the behavior of your Spring Boot application. They allow you to externalize configuration and work with the same application code in different environments. Types of Properties: - Application Properties: Basic application configuration - Profile-specific Properties: Environment-specific configuration...

Properties and Configuration :: Spring Boot?

@TestPropertySource on tests # 3. @SpringBootTest properties # 4. Command line arguments # 5. SPRING_APPLICATION_JSON (inline JSON embedded in env variable) # 6. ServletConfig init parameters # 7. ServletContext init parameters # 8. java:comp/env JNDI attributes # 9. System.getProperties() # 10. OS environment variables # 11. RandomValuePropertySource (random.*) # 12. Profile-specific application-...

Properties with Spring and Spring Boot - GeeksforGeeks?

1. What are Spring Boot Properties? Spring Boot properties are configuration settings that control the behavior of your Spring Boot application. They allow you to externalize configuration and work with the same application code in different environments. Types of Properties: - Application Properties: Basic application configuration - Profile-specific Properties: Environment-specific configuration...

How to Access Values from application.properties in Spring ...?

Common Properties by Category 4.1 Core Spring Properties # Application basic config spring.application.name=my-service spring.profiles.active=dev spring.main.banner-mode=console spring.main.lazy-initialization=true # Internationalization spring.messages.basename=messages spring.web.locale=en_US # File upload spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB...

Spring Boot Properties: Complete Tutorial - DEV Community?

Benefits: - Externalized Configuration: Separate configuration from code - Environment-specific Settings: Different configurations for dev, test, prod - No Code Changes: Modify behavior without recompiling - Type Safety: Strongly bound to configuration classes - Auto-completion: IDE support for property names When to Use: - Database connections - Server configuration - Feature toggles - External s...