Posts

Showing posts with the label Spring Boot Annotations

Spring Boot @ConditionalOnExpression Annotation Example

Image
In this section we will learn about  @ConditionalOnExpression   Annotation. The  @ConditionalOnExpression  annotation allows configurations based on the result of a SpEL expression.  The  @ConditionalOnExpression  annotation may be used on any class annotated with @Configuration ,  @Component ,  @Service  &  @Repository  or on methods annotated with  @Bean . 1. Using @ConditionalOnExpression on @Bean method To illustrate the use of  @ConditionalOnExpression , we will develop a basic notification system. To keep things simple for now, let's assume we want to send email notifications and sms notifications. Define our application custom configuration properties, notification.enabled = true notification.sms.enabled = true notification.email.enabled = false notification.twitter.enabled = true Next,  we'll need to create a simple service to send a notification. For example, consider the Notification Sender interface: public interface NotificationService { } In this example, the S

Spring Boot @ConditionalOnMissingBean Annotation Example

Image
In this section we will learn about @ ConditionalOnMissingBean   Annotation. You can use  @ ConditionalOnMissingBean  if you want to load a bean only if another bean doesn’t exist in the application context. @Bean @ConditionalOnMissingBean public NotificationService emailNotificationService () { return new EmailNotificationService(); } This example loads the EmailNotificationService into the application context if there is no other NotificationService exist in application context.  The following example creates a Spring Boot web application which uses  @ConditionalOnMissingBean annotation .  Project Directory 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 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion >4.0.0</ mode