Spring Profiles

Spring Profiles

Thanks to,Credit and References :

https://www.javadevjournal.com/spring/spring-profiles/

https://www.amitph.com/how-to-use-spring-profiles/

Introduction

Spring Profiles provides a powerful and easy way to control code and configuration based on the environment. Using?Spring Profiles?it’s possible to?segregate parts of our application and make it only available in certain environments. We can use?@Profile?annotation to limit the availability of any?@Component??or?@Configuration.

What is Spring Profile

Spring Profiles helps segregating your application configurations, and make them available only in certain environments.

An application run on many different environments. For example, Dev, QA, Test, Stage, Production etc. Therefore, an application may need different configurations on different environments.. In other words, configurations like databases, messaging systems, server ports, security will be different from environment to environment.

Spring Profiles helps to easily set right configurations on right environments. Otherwise, without having Spring Profiles it is a big pain to manage environment specific configurations. For example, your application may have to rely on the configurations externalised on the environments. Obviously, that is fairly difficult to keep in-sync. Otherwise, you will have to write bunch of factory like components to make certain things available based on certain environment specific parameters parameters.

?

1. Use?@Profile?Annotation

Main entry point for the Spring Profile is?@Profile?annotation which can be used to group things together. Let’s take a simple example for a Database connection bean where we want to make sure that certain DB connection should be active only?in DEV mode but not in production or QA / Staging. We can use?@Profile?annotation to achieve this.

@Service
@Profile("development")
public class DevDBConnection implements  DatabaseService {
    
    @Override
    public void getDBConnection() {
        System.out.println("DEV DB connection established");
    }
}        

Since we annotated DevDBConnection bean with “development” profile,?it will only be available in the Spring container if?development profile?is active, in other words, if development profile is not active, this bean will not be available/active.?

Default profile used by Spring profile is the?default. All the beans with no profile annotation are specified belongs to the default profile. We can also set default profile in Spring Boot by?@Profile("default")?or?@Profile({"default","development"}).

?

2. Use @Profile Annotation

Spring Boot?provides multiple ways to active profile. We can pass profile information through the command line or use?application.properties, Spring Boot also provide a way to set profile programmatically.

2.1 Using Command Line

We can pass profile information to Spring Boot using the switch through command prompt?—spring.profiles.active=development,staging

?

2.2 Using Property File

We can use standard Spring environment?property spring.profiles.active property in our application.properties or?application.yaml?to specify active profiles.

spring.profiles.active=development,staging        

?

2.3 Programmatically setting profile

We can programmatically set active profile by calling?setAdditionalProfiles(...)?method provided by SpringApplication class

SpringApplication app = new SpringApplication(Application.class);
app.setAdditionalProfiles("development","production");        

Take a note that spring.profiles.active property follows same ordering rule as followed by other properties defined by Spring Boot. Highest property source will overwrite any other property defined in the hierarchy. Please refer to Spring Boot documentation to understand how Spring Boot read these properties.

3. Profile Specific Configurations

One of the most interesting and powerful features provided by Spring Boot is the ability to define profile specific application.properties file and active these by main application.properties file.

To use profile specific configuration files, we need to the naming convention of?application-{profile}.properties?where profile defines the name?of the intended profile. Profile specific files will be loaded from the same location as?application.properties?file, also be aware that profile specific properties will override properties defined in the default application.properties?irrespective of whether the profile-specific files are inside or outside your packaged jar.

To understand it completely, let’s take the same example of Database configuration where we want to define different DB configurations for Development and Production.To achieve this using configuration files, we will define 2 configuration file namely?<em>application-production.properties</em>?and?<em>application-</em>development.properties.?

application-production.properties

db.url=jdbc:oracle:thin:@<host>:1521:<sid>
db.driver=oracle.jdbc.driver.OracleDriver
db.username=<username>
db.password=<password>
db.tableprefix=         

application-development.properties

db.url=jdbc:hsqldb:file:configurations
db.driver=org.hsqldb.jdbcDriver
db.username=sa
db.password=
db.tableprefix=        

In above example we used HSQL for Development while we want to use Oracle for production and based on the active profile, we can easily switch DB configurations.

Please read?@ConfigurationProperties in Spring Boot?to understand how Spring Boot Configuration works

4. Complete Example

Here is a complete example to understand how Spring Boot Profile work.

DataBase Service

public interface DatabaseService {

    void getDBConnection();
}        

Development Profile

@Service
@Profile("development")
public class DevDBConnection implements  DatabaseService {

    @Override
    public void getDBConnection() {
        System.out.println("DEV DB connection established");
    }
}        

Production Profile

@Service
@Profile("production")
public class ProdDBConnection implements DatabaseService {

    @Override
    public void getDBConnection() {
        
        System.out.println("Product DB connection establish");
    }
}        

Spring Boot Runner

@SpringBootApplication
public class SpringbootTutorialsApplication implements CommandLineRunner{

   @Autowired
    DatabaseService databaseService;

    public static void main(String[] args) {

      SpringApplication.run(SpringbootTutorialsApplication.class, args);
   }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        databaseService.getDBConnection();
    }
}        

output

if you run above example with development profile as active profile, we will have the following output

DEV DB connection established        



Murad Shahin

System Integration Engineer @CBOJ (Middleware) #Certified Mulesoft developer #Anypoint Platform #Java Spring Boot #AWS #Jenkins #Android #Nodejs #Banking #Micorservices

3 年

We can also use a config server to manage that

回复

要查看或添加评论,请登录

Omar Ismail的更多文章

社区洞察

其他会员也浏览了