Posts

Showing posts with the label Spring Core Annotations

Spring @PropertySource Annotation Example

Image
In this section we will learn about @PropertySource  Annotation. The  @PropertySource  is a convenient annotation for including PropertySource to Spring's Environment and allowing to inject properties via @Value into class attributes.  This annotation is used with @Configuration classes. Spring @PropertySource annotation is repeatable, means you can have multiple @PropertySource on a Configuration class. This feature is available if you are using Java 8 or higher version.  For earlier java versions, @PropertySources was the way to provide multiple property files to the configuration class. The following example creates a Spring Boot web application which uses  @PropertySource annotation . Project Directory db.properties DB_DRIVER_CLASS = com.mysql.jdbc.Driver DB_URL = jdbc:mysql://localhost:3306/Demo DB_USERNAME = knf DB_PASSWORD = root message.properties hello.message = Hello World knowledgefactory.properties knf.message = Hi, Greetings from knowledgefactory.net. language.lis

Spring @Lazy Annotation Example

Image
In this section we will learn about @Lazy  Annotation. By default, the Spring IoC container creates and initializes all singleton beans at time of application startup.  This default behavior ensures that any possible error caught immediately. This feature is really good to avoid any runtime errors but there are a number of use cases when we do not want Spring IoC to create beans on startup but create it when requested by the application. We can prevent this pre-initialization of a singleton bean by using the @Lazy annotation. The @Lazy annotation may be used on any class annotated with @Component , @Service & @Repository or on methods annotated with @Bean . 1. Using @Lazy on @Bean method If @Lazy annotation present on a @Bean method, Spring initializes that specific bean lazily. Let’s have a look at example. In following example, we have configured 2 beans and SMSService bean marked with @Lazy . public class EmailService { public EmailService () { System . out .pr