Saturday, 4 August 2018

Spring Framework

Spring Framework
Spring Core
Cover spring core concepts like dependeny injection. Read more>>
Spring MVC
MVC stands for Model View Controller. Spring Web MVC is a web framework built on top of Servlet API. it is built on controller pattern and MVC guide lines. Read more>>
Spring Boot
Introduction to Spring Boot
By using spring boot, you can create standalone spring applications. Any typical web application requires Servlet container, caching library, messaging service etc., Read more>>
Actuator
Spring Boot actuator is used to monitor the running spring boot application. It provides Health, info and JMX endpoints. Read more>>
Aspects
Aspect is a block of code that is injected into application at run time. Aspects are used to solve cross-cutting concerns. Read more>>
Spring ArangoDB
Spring and ArangoDB integration Read more>>
Spring Batch
Batch Processing is a way of executing list of tasks as a group. Most of the batch processing applications will execute without any user interaction. Read more>>
Spring Boot 3
Spring boot 3 tutorial Read more>>
Spring Cache
Spring Cache is used to cache data items. Read more>>
Spring cloud
Api gateway example etc., Read more>>
Spring Data REST
You are going to learn how to build REST APIs for spring JPA Repositories. Read more>>
Spring Developement Tools
Developement tools are used to do effective applicaiton development Read more>>
Flyway integration
Integrate Spring with Flyway Read more>>
GraphQL
GraphQL with spring boot hands on Read more>>
JDBC
JDBC with spring boot hands on Read more>>
Integration
Spring integration is an extension to spring programming model, implements most of the Enterprise integration patterns (https://www.enterpriseintegrationpatterns.com/) Read more>>
Integration
Spring integration is an extension to spring programming model, implements most of the Enterprise integration patterns (https://www.enterpriseintegrationpatterns.com/) Read more>>
Kafka
spring and Kafka examples Read more>>
log4j2
spring and log4j2 examples Read more>>
OpenAPI
spring and openAPI examples Read more>>
Quartz: Job scheduling
Integrate quartz job scheduling library with spring boot. Read more>>
Rate limiter integration
Integrate rate limitier libraries with spring boot. Read more>>
REST API Development
Covers CURD operations using Spring REST Read more>>
RestTemplate
RestTemplate as HTTP Client to perform CRUD Operations. Read more>>
Security
Covers how can we achieve Authentication and Authroization via spring security Read more>>
Swagger
Spring and swagger integration Read more>>
Spring Data JPA
Spring data is a spring project to perform CRUD operations on databases. Spring Data JPA enhances the standard JPA (Java Persistence API) using spring framework. Read more>>
Spring Shell
Spring Shell is a Java Library used to create a runnable application where the user enter textual commands that will get executed until the program terminates. Read more>>
WebAppliation Development
You are going to learn how to build web applications in spring boot from scratch Read more>>
Webflux
Spring WebFlux is a reactive web framework for spring. Read more>>
Test Spring Boot Applications
This tutorial covers how to test dao, serivce and controller layer components. Read more>>
Miscellaneous
You can get useful spring boot applications here. Read more>>

Spring Boot: Profile specific properties

In my previous posts, I explained about spring boot profiles, in this post, I am going to explain how can we configure profile specific properties.

How to define profile specific properties?
Profile specific properties are specified using below naming convention.

Syntax
application-{profile}.properties

Let me explain with an example.

application.properties
# Applicaiton name is common for all the profiles
applicationName=Chat Server

# Set the profile to dev
spring.profiles.active=dev
As you see above file, I set 'dev' as my active profile.

application-dev.properties
systemURL=chatserver.dev.com
version=1.5
environment=Development

application-prod.properties
systemURL=chatserver.prod.com
version=1.4
environment=Production


application-test.properties
systemURL=chatserver.test.com
version=1.4
environment=Testing

ApplicationConfigurations.java
package com.sample.myApp.configurations;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties
public class ApplicationConfigurations {

 private String systemURL;
 private String version;
 private String environment;
 private String applicationName;

 public String getApplicationName() {
  return applicationName;
 }

 public void setApplicationName(String applicationName) {
  this.applicationName = applicationName;
 }

 public String getSystemURL() {
  return systemURL;
 }

 public void setSystemURL(String systemURL) {
  this.systemURL = systemURL;
 }

 public String getVersion() {
  return version;
 }

 public void setVersion(String version) {
  this.version = version;
 }

 public String getEnvironment() {
  return environment;
 }

 public void setEnvironment(String environment) {
  this.environment = environment;
 }

}

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.sample.myApp.configurations.ApplicationConfigurations;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  ApplicationConfigurations appConfig = applicationContext.getBean(ApplicationConfigurations.class);

  System.out.println("****************************************");
  System.out.println("Application Name : " + appConfig.getApplicationName());
  System.out.println("Environment : " + appConfig.getEnvironment());
  System.out.println("System URL : " + appConfig.getSystemURL());
  System.out.println("Version : " + appConfig.getVersion());
  System.out.println("****************************************");

  applicationContext.close();
 }

}


When you ran ‘Application.java’, you can able to see below messages in the console.
****************************************
Application Name : Chat Server
Environment : Developement
System URL : chatserver.dev.com
Version : 1.5
****************************************


Project structure looks like below.


What is the behavior, if no profiles are activated?
If no profiles are activated, then properties are loaded from 'application.properties' file. If you specify a profile, then profile-specific files always override the non-specific ones.

What is the behavior, when I specify multiple profiles?
If several profiles are specified, a last-wins strategy applies.





Previous                                                 Next                                                 Home

Spring boot: Activate profiles programmatically

There are couple of ways to set the active profiles in spring boot application.
Before running your application,

a.   You can call 'SpringApplication.setAdditionalProfiles(…​)' method,
b.   Activate profiles by using Spring’s ConfigurableEnvironment interface

Using 'SpringApplication.setAdditionalProfiles(…​)' method
Below statements set dev, prod profiles to the application.

SpringApplication application = new SpringApplication(Application.class);
application.setAdditionalProfiles("dev","prod");
ConfigurableApplicationContext applicationContext = application.run(args);

Find the below working example.

DevProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("dev")
public class DevProfile {

 public DevProfile() {
  System.out.println("********************************");
  System.out.println("Dev profile is called");
  System.out.println("********************************");
 }
}

ProdProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("prod")
public class ProdProfile {
 public ProdProfile() {
  System.out.println("********************************");
  System.out.println("Prod profile is called");
  System.out.println("********************************");
 }
}

TestProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("test")
public class TestProfile {
 public TestProfile() {
  System.out.println("********************************");
  System.out.println("Test profile is called");
  System.out.println("********************************");
 }
}

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  SpringApplication application = new SpringApplication(Application.class);
  application.setAdditionalProfiles("dev","prod");
  ConfigurableApplicationContext applicationContext = application.run(args);
  applicationContext.close();
 }

}

When you ran ‘Application.java’, you can able to see below messages in the console.
********************************
Dev profile is called
********************************
********************************
Prod profile is called
********************************

Project structure looks like below.





Activate profiles by using Spring’s ConfigurableEnvironment interface
You can also activate the profile using 'ConfigurableEnvironment'.

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("someProfile");

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  SpringApplication application = new SpringApplication(Application.class);

  ConfigurableEnvironment environment = new StandardEnvironment();
  environment.setActiveProfiles("dev", "prod");

  application.setEnvironment(environment);

  ConfigurableApplicationContext applicationContext = application.run(args);
  
  applicationContext.close();
 }

}







Previous                                                 Next                                                 Home

Spring boot: How to get all active profiles

Below statements return all the active profiles.

Environment environment = applicationContext.getBean(Environment.class);
for (final String profileName : environment.getActiveProfiles()) {
         System.out.println("Currently active profile : " + profileName);
}

Find the below working application.

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  Environment environment = applicationContext.getBean(Environment.class);
  for (final String profileName : environment.getActiveProfiles()) {
   System.out.println("Currently active profile : " + profileName);
  }

  applicationContext.close();
 }

}



Previous                                                 Next                                                 Home

Spring boot: Profiles

In this post, I am going to show you how to use spring profiles.

We can map our beans, configurations to specific profiles (Ex: prod, dev, test etc.,) and can use when the respective profiles are activated.

How can I mark a component (or) configuration with profile?
Just add @Profile annotation on top of a @Component, @Configuration class.

How to activate a profile?
By adding the property 'spring.profiles.active' in application.properties file, you can activate the profile.

Ex
spring.profiles.active=dev,prod

Above statement activates dev, prod profiles.

Let me explain with an example. I am going to create 3 profiles dev, prod and test. When I activate the test profile and ran the application, only test profile specific bean is getting instantiated by spring framework.

DevProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("dev")
public class DevProfile {

 public DevProfile() {
  System.out.println("********************************");
  System.out.println("Dev profile is called");
  System.out.println("********************************");
 }
}

ProdProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("prod")
public class ProdProfile {
 public ProdProfile() {
  System.out.println("********************************");
  System.out.println("Prod profile is called");
  System.out.println("********************************");
 }
}

TestProfile.java
package com.sample.myApp.model;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("test")
public class TestProfile {
 public TestProfile() {
  System.out.println("********************************");
  System.out.println("Test profile is called");
  System.out.println("********************************");
 }
}


application.properties
spring.profiles.active=test

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  applicationContext.close();
 }

}

When you ran Application.java, you can able to see below messages in the console.
********************************
Test profile is called
********************************


Project structure looks like below.


Profile names and not operator
You can prefix a profile name with a not (!) operator.

Example
@Profile("!dev")

In the above example, a component is active only if the dev profile is not active.

What is default profile?
If a bean don’t specify a profile, then it belongs to ‘default’ profile. You can specify the default profile using the property ‘spring.profiles.default’. If you don’t specify the profile to use, then spring uses default profile configure using the property ‘spring.profiles.default’

How to activate the profile using command line argument?
Pass below command line argument to activate the ‘dev’ profile.
-Dspring.profiles.active=dev


Previous                                                 Next                                                 Home

Spring Boot: Validating properties

If you annotate @ConfigurationProperties classes with @Validated annotation, then spring boot validate the properties.

@Component
@ConfigurationProperties
@Validated
public class MyConfigurations {

         @NotEmpty
         private String appName;
        
         ......
         ......
        
}

As you see above code, @NotEmpty annotation, makes sure that the appName must not be empty.

Find the below working application.

application.properties
appName=
version=1.25

MyConfigurations.java
package com.sample.myApp.model;

import javax.validation.constraints.NotEmpty;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Component
@ConfigurationProperties
@Validated
public class MyConfigurations {

 @NotEmpty
 private String appName;
 private double version;

 public String getAppName() {
  return appName;
 }

 public void setAppName(String appName) {
  this.appName = appName;
 }

 public double getVersion() {
  return version;
 }

 public void setVersion(double version) {
  this.version = version;
 }
}


Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.sample.myApp.model.MyConfigurations;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  MyConfigurations myConfiguration = applicationContext.getBean(MyConfigurations.class);

  System.out.println("****************************************************");
  System.out.printf("Application Name : %s\n", myConfiguration.getAppName());
  System.out.printf("Version : %f\n", myConfiguration.getVersion());
  System.out.println("****************************************************");

  applicationContext.close();

 }

}

When you ran above application, you will endup in below validation failure.
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under '' to com.sample.myApp.model.MyConfigurations failed:

    Property: .appName
    Value: 
    Origin: class path resource [application.properties]:2:0
    Reason: must not be empty


Action:

Update your application's configuration

Spring boot supports all the annotations in 'javax.validation.constraints' package.


Project structure looks like below.




Previous                                                 Next                                                 Home