Skip to main content

Posts

Showing posts with the label SpringBoot

Microservices - Config management using Spring cloud bus and Rabbit MQ

In this tutorial we will learn how to add Rabbit MQ capabilities to our Spring cloud config server so any changes to configurations can be pushed to all connected applications during runtime. We need such kind of behaviour when we need to refresh the properties without restarting our application. Below is the overall architecture for this complete setup. Spring Cloud Config Server Spring cloud config server is used to setup the distributed configuration using GIT or local file system where we can keep our configuration files and serve as them from Spring cloud config server. Client application just has to connect with config server by providing their application and profile name for specific configuration. Please refer below link where I have explained more about cloud config and how to code it. https://www.thetechnojournals.com/2019/10/spring-cloud-config.html Install Rabbit MQ Please refer below link on how to install rabbit-mq and virtual host verification. https://w...

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to ...

How to handle exceptions in REST services (JAX-RS and SpringBoot)

Exception handling is vital aspect of any application or service. Exceptions should be handled properly and appropriate messages must be generated to end user or service in case of any exception. Same applies to REST services also whether they are used by some front-end application or some other service uses it to perform some operations. It becomes tricky when we deal with REST services as we need to expose all the supported status codes for both success and error response which our service can generate, so client application or service can handle them appropriately.  Below are some samples of the status code. 200 - OK (API processes the request perfectly) 404 - Not found (Request URI or resource is not available) 500 - Internal server error (Request failed  due to some error at runtime at service side) There are multiple ways to handle the exceptions which we will see in below sections. Manual exception handling We can handle the exception manually also like usin...

Spring boot application events

Spring boot provides an easy and quick way to implement the event listeners. Spring boot generates multiple events during it's application lifecycle. We will see the below events which are provided by spring application under "org.springframework.boot.context.event" Java package. Thanks to spring that we don't need to focus on writing the listeners but the business logics which we want to execute during a specific event and to do that we just need to annotate our business method with @EventListener. ApplicationContextInitializedEvent Event published when a SpringApplication is starting up and the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded. Implementation and code example ApplicationEnvironmentPreparedEvent Event published when a SpringApplication is starting up and the Environment is first available for inspection and modification. Implementation and code example ...

ApplicationStartedEvent and ApplicationReadyEvent code example

Both ApplicationStartedEvent and ApplicationReadyEvent executes once service is started but there is little difference that ApplicationReadyEvent executes when application is ready to serve the request. Will see the implementation for both in below code. Since both are starting after application is up, we can use annotation based listener in this case. We will see the implementation In two different ways. Using Annotation To use annotation based listener we can define below code in any spring managed bean, like Component, Configuration etc. @EventListener(ApplicationReadyEvent.class) public void applicationReadyEvent() { System.out.println("Executing ApplicationReadyEvent..."); } @EventListener(ApplicationStartedEvent.class) public void applicationStartedEvent() { System.out.println("Executing ApplicationStartedEvent..."); } Registering with SpringApplication Below code shows the event listener creation with SpringApplication. @SpringBootApplicat...

ApplicationFailedEvent code example

ApplicationFailedEvent executes when application is failed to start. For example if application port is already in use or any other error during start. We can use this event listener to email the error or executing any script upon failure. In this example we will try to run the application twice to generate the failed event. SpringBootTutorialApplication @SpringBootApplication public class SpringBootTutorialApplication{ public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class); //register ApplicationFailedEvent event app.addListeners((ApplicationFailedEvent event)->{ System.out.println("Executing ApplicationFailedEvent..."); }); //start the application app.run(args); } } Try to run the application twice on the same port so in second attempt it will generate the error during start as one instance is already running on that port. Output Failed event execution statement is highligh...

ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent code example

Both ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent are executed before the application start and may be useful to modify or read the application or environment at runtime such as profiles. SpringBootTutorialApplication.java @SpringBootApplication public class SpringBootTutorialApplication implements AsyncConfigurer{ public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class); //register ApplicationEnvironmentPreparedEvent app.addListeners((ApplicationEnvironmentPreparedEvent event)->{ System.out.println("Executing ApplicationEnvironmentPreparedEvent..."); }); //register ApplicationStartingEvent app.addListeners((ApplicationStartingEvent event)->{ System.out.println("Executing ApplicationStartingEvent..."); }); //start the application app.run(args); } } Output Below output shows that both the events are executed before application start. Exe...

ApplicationContextInitializedEvent Code Example

ApplicationContextInitializedEvent provides you access to ApplicationContext and SpringApplication using which you can do many things like adding listeners at runtime, invoking events etc. In below code we will see how to register this event and fail the application if it finds the value true for given property. SpringBootTutorialApplication.java public class SpringBootTutorialApplication{ public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class); //register ApplicationContextInitializedEvent event app.addListeners((ApplicationContextInitializedEvent event)->{ System.out.println("Executing ApplicationContextInitializedEvent..."); //get the property value String shouldFailed = event.getApplicationContext() .getEnvironment().getProperty("should.app.failed"); if("true".equals(shouldFailed)) { //invoke failed event event.getApplicationContext() .pu...