Showing posts with the label Spring Core Annotations

Spring @Import Annotation Example

In this section we will learn about @Import  Annotation. When we run a Spring application, the packages are scanned. Beans are created from @Component , @Service , @Repository and @Configuration classes. Scanning takes place using the @ComponentScan annotation.  It is contained inside the @SpringBootApplication annotation, with which the main class of the application is annotated. All classes that are in the same package as the class with the @ComponentScan (that is, with the @SpringBootApplication ) as well as in the subpackages of this package are scanned. If you generate a Spring Boot project on the  site, you can see: the main class with the annotation with the @SpringBootApplication is in the root package. This means that by default all classes that are below are scanned. That is, the Main Application can be in the package, but not in the java folder without the package. Correct Structure: The EmailNotificationService and SMSNotifica

Spring @DependsOn Annotation Example

In this section we will learn about @DependsOn  Annotation. The order in which Spring container creating beans cannot be predicted.  When we need spring to create certain bean before creating our bean, we can choose the @DependsOn annotation for managing bean creation order.  The @DependsOn annotation can force the Spring IoC container to initialize one or more beans before the bean which is annotated by @DependsOn annotation. The @DependsOn annotation may be used on any class annotated with @Component , @Service & @Repository or on methods annotated with @Bean . 1. Using @DependsOn on @Bean method @DependsOn annotation accepts array of bean names to specify the dependency beans. And again, here the order we keep the bean name in array is the order for bean creation. For the below code, the order of bean creation is twitterService , emailService , smsService . @Configuration public class AppConfig { @Bean @DependsOn ({ "twitterService" , "emailService&