How to Run a CommandLineRunner Bean Conditionally in Spring Boot

This article shows different ways to run a CommandLineRunner bean conditionally in a Spring Boot application. Table of contents: 1. Using @ConditionalOnProperty 2. Using Environment 3. Using Spring Profiles 4. Check the Presence of Other Beans 4.1 Using @ConditionalOnBean 4.2 Using @ConditionalOnMissingBean 5. Download Source Code 6. References P.S. Tested with Spring Boot 3.1.2 1. …

Read more

Spring Boot – Profile based properties and yaml example

In Spring Boot, it picks .properties or .yaml files in the following sequences : application-{profile}.properties and YAML variants application.properties and YAML variants Note For detail, sequence and order, please refer to this official Externalized Configuration documentation. Tested : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. @ConfigurationProperties Read the …

Read more

Spring Boot Profiles example

In this article, we will show you how to use @Profile in Spring Boot and also how to test it. Tested with : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. Project Dependency pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>spring-boot-profile</artifactId> <packaging>jar</packaging> <name>Spring Boot Profiles Example</name> …

Read more

Spring MVC – How to set active profile

In this example, we will show you how to set active @Profile in a Spring MVC web application. @Profile Examples @Configuration public class AppConfig { @Profile("dev") @Bean public CacheManager cacheManager() { //… } @Profile("live") @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { //… } @Profile("testdb") @Bean public DataSource dataSource() { //… } } To set active @Profile in …

Read more

Spring Profiles example

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment. In this tutorial, we will show you a Spring @Profile application, which does …

Read more