Spring Boot Annotations With Examples - JavaTechOnline
Spring Boot Annotations With Examples - JavaTechOnline
Spring Boot
java
Spring
Here in this article on ‘Spring Boot Annotations With Examples’, we will discuss about all annotations that we use in a Spring
Boot Application. Annotations which are not part of this article, will be included in other respective articles. Link will be provided
here only for easy navigation. In addition, you can also check one more article ‘Annotations in Java‘ in order to know annotation
basics and how to create custom annotations in Java. Let’s start discussing our topic ‘Spring Boot Annotations With Examples’.
Table of Contents
Annotation Basics
What is The IoC container?
What is an Application Context in Spring Framework?
What is Spring Bean or Components?
What is Component Scanning?
When to use Component Scanning in a Spring Boot Application?
Spring Annotations vs Spring Boot Annotations
Annotations that Supports to create a Spring Bean
@Component
@Controller
@RestController
@Service
@Repository
@Configuration
@Bean
@Bean vs @Component
Configuration Annotations
@ComponentScan
@Import
@PropertySource
@PropertySources (For Multiple Property Locations)
@Value
@Value for default Value
@Value for multiple values
Spring Boot Specific Annotations
@SpringBootApplication (@Configuration + @ComponentScan + @EnableAutoConfiguration)
@EnableAutoConfiguration
Use of ‘exclude’ in @EnableAutoConfiguration
Use of ‘excludeName’ in @EnableAutoConfiguration
@SpringBootConfiguration
@ConfigurationProperties
@EnableConfigurationProperties
@EnableConfigurationPropertiesScan
@EntityScan and @EnableJpaRepositories
Links to Other Annotations
1) Spring Boot Bean Annotations With Examples
2) Spring Boot MVC & REST Annotations With Examples
3) Spring Boot Security, Scheduling and Transactions Annotations With Examples
4) Spring Boot Errors, Exceptions and AOP Annotations With Examples
Where can we use Annotations?
1) Class instance creation expression
2) Type cast
3) implements clause
4) Thrown exception declaration
Annotation Basics
Before discussing about ‘Spring Boot Annotations With Examples’, let’s first talk about some basic terminologies used during
the explanation of annotations.
Next annotations in our topic ‘Spring Boot Annotations With Examples’ are the stereotype annotations.
@Component
@Complonent annotation is also an important & most widely used at the class level. This is a generic stereotype annotation
which indicates that the class is a Spring-managed bean/component. @Component is a class level annotation. Other
stereotypes are a specialization of @Component. During the component scanning, Spring Framework automatically discovers
the classes annotated with @Component, It registers them into the Application Context as a Spring Bean.
Applying @Component annotation on a class means that we are marking the class to work as Spring-managed
bean/component. For example, observe the code below:
@Component
class MyBean { }
On writing a class like above, Spring will create a bean instance with name ‘myBean’. Please keep in mind that, By default, the
bean instances of this class have the same name as the class name with a lowercase initial. However, we can explicitly specify a
different name using the optional argument of this annotation like below.
@Component("myTestBean")
class MyBean { }
@Controller
@Controller tells Spring Framework that the class annotated with @Controller will work as a controller in the Spring MVC
project.
@RestController
@RestController tells Spring Framework that the class annotated with @RestController will work as a controller in a Spring REST
project.
@Service
@Service tells Spring Framework that the class annotated with @Service is a part of service layer and it will include business
logics of the application.
@Repository
@Repository tells Spring Framework that the class annotated with @Repository is a part of data access layer and it will include
logics of accessing data from the database in the application.
Apart from Stereotype annotations, we have two annotations that are generally used together: @Configuration & @Bean.
@Configuration
We apply this annotation on classes. When we apply this to a class, that class will act as a configuration by itself. Generally the
class annotated with @Configuration has bean definitions as an alternative to <bean/> tag of an XML configuration. It also
represents a configuration using Java class. Moreover the class will have methods to instantiate and configure the
dependencies. For example :
@Configuration
public class AppConfig {
@Bean
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate();
}
}
♥ The benefit of creating an object via this method is that you will have only one instance of it. You don’t need to create the
object multiple times when required. Now you can call it anywhere in your code.
@Bean
This is the basic annotation and important for our topic ‘Spring Boot Annotations With Examples’.
We use @Bean at method level. If you remember the xml configuration of a Spring, It is a direct analog of the
XML <bean/> element. It creates Spring beans and generally used with @Configuration. As aforementioned, a class
with @Configuration (we can call it as a Configuration class) will have methods to instantiate objects and configure
dependencies. Such methods will have @Bean annotation.
By default, the bean name will be the same as the method name. It instantiates and returns the actual bean. The annotated
method produces a bean managed by the Spring IoC container. For example:
@Configuration
public class AppConfig {
@Bean
public Employee employee() {
return new Employee();
}
@Bean
public Address address() {
return new Address();
}
}
For the sake of comparison, the configuration above is exactly equivalent to the following Spring XML:
<beans>
<bean name="employee" class="com.dev.Employee"/>
<bean name="address" class="com.dev.Address"/>
</beans>
The annotation supports most of the attributes offered by <bean/>, such as: init-method, destroy-method, autowiring, lazy-
init, dependency-check, depends-on and scope.
@Bean vs @Component
@Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as
the bean name. @Bean annotation has to be used within the class and that class should be annotated
with @Configuration. However, @Component needs not to be used with the @Configuration. @Component auto detects and
configures the beans using classpath scanning, whereas @Bean explicitly declares a single bean, rather than letting Spring do it
automatically.
Configuration Annotations
Next annotations in our article ‘Spring Boot Annotations with Examples’ are for Configurations. Since Spring Framework is
healthy in configurations, we can’t avoid learning annotations on configurations. No doubt, they save us from complex coding
effort.
@ComponentScan
Spring container detects Spring managed components with the help of @ComponentScan. Once you use this annotation, you
tell the Spring container where to look for Spring components. When a Spring application starts, Spring container needs the
information to locate and register all the Spring components with the application context. However It can auto scan all classes
annotated with the stereotype annotations such as @Component, @Controller, @Service, and @Repository from pre-defined
project packages.
The @ComponentScan annotation is used with the @Configuration annotation to ask Spring the packages to scan for
annotated components. @ComponentScan is also used to specify base packages and base package classes using basePackages
or basePackageClasses attributes of @ComponentScan. For example :
import com.springframework.javatechonline.example.package2.Bean1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.springframework.javatechonline.example.package1",
"com.springframework.javatechonline.example.package3",
"com.springframework.javatechonline.example.package4"},
basePackageClasses = Bean1.class
)
public class SpringApplicationComponentScanExample {
....
}
Here the @ComponentScan annotation uses the basePackages attribute to specify three packages including their subpackages
that will be scanned by the Spring container. Moreover the annotation also uses the basePackageClasses attribute to declare the
Bean1 class, whose package Spring Boot will scan.
Moreover, In a Spring Boot project, we typically apply the @SpringBootApplication annotation on the main application class.
Internally, @SpringBootApplication is a combination of the @Configuration,
@ComponentScan, and @EnableAutoConfiguration annotations. Further, with this default setting, Spring Boot will auto scan for
components in the current package (containing the SpringBoot main class) and its sub packages.
@Import
Suppose we have multiple Java configuration classes annotated by @Configuration. @Import imports one or more Java
configuration classes. Moreover, it has the capability to group multiple configuration classes. We use this annotation where
one @Configuration class logically imports the bean definitions defined by another. For example:
@Configuration
@Import({ DataSourceConfig.class, MyCustomConfig.class })
public class AppConfig extends ConfigurationSupport {
// @Bean methods here that can reference @Bean methods in DataSourceConfig or MyCustomConfig
}
@Configuration
public class DataSourceConfig {...}
@Component
public class MyCustomConfig {...}
@PropertySource
If you create a Spring Boot Starter project using an IDE such as STS, application.properties comes under resources folder by
default. In contrast, You can provide the name & location of the properties file (containing the key/value pair) as per your
convenience by using @PropertySource. Moreover, this annotation provides a convenient and declarative mechanism for adding
a PropertySource to Spring’s Environment. For example,
@Configuration
@PropertySource("classpath:/com/dev/javatechonline/app.properties")
public class MyClass {
}
However, we can also write the same code in another way as below. The @PropertySource annotation is repeatable according to
Java 8 conventions. Therefore, if we’re using Java 8 or higher, we can use this annotation to define multiple property locations.
For example:
@Configuration
@PropertySource("classpath:/com/dev/javatechonline/app1.properties")
@PropertySource("classpath:/com/dev/javatechonline/app2.properties")
public class MyClass { }
♥ Note : If there is any conflict in names such as the same name of the properties, the last source read will always take
precedence.
@Value
We can use this annotation to inject values into fields of Spring managed beans. We can apply it at field or constructor or
method parameter level. For example, let’s first define a property file, then inject values of properties using @Value.
server.port=9898
server.ip= 10.10.10.9
emp.department= HR
columnNames=EmpName,EmpSal,EmpId,EmpDept
@Value("${server.ip}")
private String serverIP;
Suppose we have not defined a property in the properties file. In that case we can provide a default value for that property.
Here is the example:
@Value("${emp.department:Admin}")
private String empDepartment;
Here, the value Admin will be injected for the property emp.department. However, if we have defined the property in the
properties file, the value of property file will override it.
♥ Note : If the same property is defined as a system property and also in the properties file, then the system property would
take preference.
Sometimes, we need to inject multiple values of a single property. We can conveniently define them as comma-separated
values for the single property in the properties file. Further, we can easily inject them into property that is in the form of an
array. For example:
@Value("${columnNames}")
private String[] columnNames;
In fact @SpringBootApplication is a combination of three annotations with their default values. They are @Configuration,
@ComponentScan, and @EnableAutoConfiguration. Therefore, we can also say that @SpringBootApplication is a 3-in-1
annotation. This is an important annotation in the context of our topic ‘Spring Boot Annotations With Examples’.
We can also use above three annotations separately in place of @SpringBootApplication if we want any customized behavior of
them.
@EnableAutoConfiguration
@EnableAutoConfiguration enables auto-configuration of beans present in the classpath in Spring Boot applications. In a
nutshell, this annotation enables Spring Boot to auto-configure the application context. Therefore, it automatically creates and
registers beans that are part of the included jar file in the classpath and also the beans defined by us in the application. For
example, while creating a Spring Boot starter project when we select Spring Web and Spring Security dependency in our
classpath, Spring Boot auto-configures Tomcat, Spring MVC and Spring Security for us.
Moreover, Spring Boot considers the package of the class declaring the @EnableAutoConfiguration as the default package.
Therefore, if we apply this annotation in the root package of the application, every sub-packages & classes will be scanned. As a
result, we won’t need to explicitly declare the package names using @ComponentScan.
@Configuration
@EnableAutoConfiguration(exclude={WebSocketMessagingAutoConfiguration.class})
public class MyWebSocketApplication {
public static void main(String[] args) {
...
}
}
@Configuration
@EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoC
public class MyWebSocketApplication {
public static void main(String[] args) {
...
}
}
@SpringBootConfiguration
This annotation is a part of Spring Boot Framework. However, @SpringBootApplication inherits from it. Therefore, If an
application uses @SpringBootApplication, it is already using @SpringBootConfiguration. Moreover, It acts as an alternative to
the @Configuration annotation. The primary difference is that @SpringBootConfiguration allows configuration to be
automatically discovered. @SpringBootConfiguration indicates that the class provides configuration and also applied at the
class level. Particularly, this is useful in case of unit or integration tests. For example, observe the below code:
@SpringBootConfiguration
public class MyApplication {
@ConfigurationProperties
Spring Framework provides various ways to inject values from the properties file. One of them is by using @Value annotation.
Another one is by using @ConfigurationProperties on a configuration bean to inject properties values to a bean. But what is the
difference among both ways and what are the benefits of using @ConfigurationProperties, you will understand it at the end.
Now Let’s see how to use @ConfigurationProperties annotation to inject properties values from the application.properties or
any other properties file of your own choice.
First, let’s define some properties in our application.properties file as follows. Let’s assume that we are defining some properties
of our development working environment. Therefore, representing properties name with prefix ‘dev’.
dev.name=Development Application
dev.port=8090
dev.dburl=mongodb://mongodb.example.com:27017/
dev.dbname=employeeDB
dev.dbuser=admin
dev.dbpassword=admin
Now, create a bean class with getter and setter methods and annotate it with @ConfigurationProperties.
@ConfigurationProperties(prefix="dev")
public class MyDevAppProperties {
private String name;
private int port;
private String dburl;
private String dbname;
private String dbuser;
private String dbpassword;
Here, Spring will automatically bind any property defined in our property file that has the prefix ‘dev’ and the same name as one
of the fields in the MyDevAppProperties class.
@Configuration
@EnableConfigurationProperties(MyDevAppProperties.class)
public class MySpringBootDevApp { }
@Component
public class DevPropertiesTest implements CommandLineRunner {
@Autowired
private MyDevAppProperties devProperties;
@Override
public void run(String... args) throws Exception {
System.out.println("App Name = " + devProperties.getName());
System.out.println("DB Url = " + devProperties.getDburl());
System.out.println("DB User = " + devProperties.getDbuser());
}
}
@EnableConfigurationProperties
In order to use a configuration class in our project, we need to register it as a regular Spring bean. In this
situation @EnableConfigurationProperties annotation support us. We use this annotation to register our configuration bean
(a @ConfigurationProperties annotated class) in a Spring context. This is a convenient way to quickly
register @ConfigurationProperties annotated beans. Moreover, It is strictly coupled with @ConfiguratonProperties. For example,
you can refer @ConfigurationProperties from the previous section.
@EnableConfigurationPropertiesScan
@EnableConfigurationPropertiesScan annotation scans the packages based on the parameter value passed into it and discovers
all classes annotated with @ConfiguratonProperties under the package. For example, observe the below code:
@SpringBootApplication
@EnableConfigurationPropertiesScan(“com.dev.spring.test.annotation”)
public class MyApplication { }
Remember that, @EnableAutoConfiguration(as part of @SpringBootApplication) scans all the classes under the root package or
its sub-packages of your main application. Therefore, If the repository classes or other entity classes are not placed under the
main application package or its sub package, then the relevant package(s) should be declared in the main application
configuration class with @EntityScan and @EnableJpaRepositories annotation accordingly. For example, observe the below
code:
@EntityScan(basePackages = "com.dev.springboot.examples.entity")
@EnableJpaRepositories(basePackages = "com.dev.springboot.examples.jpa.repositories")
We can apply annotations to the declarations of different elements of a program such as to the declarations of classes, fields,
methods, and other program elements. By convention, we apply them just before the declaration of the element. Moreover, as
of the Java 8 release, we can apply annotations to the use of types. For example, below code snippets demonstrate the usage
of annotations:
2) Type cast
myString = (@NonNull String) str;
3) implements clause
class UnmodifiableList<T> implements
@Readonly List<@Readonly T> { ... }
This form of annotation is called a type annotation. For more information, see Type Annotations and Pluggable Type Systems.
However, these annotations are not in tradition at present, but in the future we can see them in the code. Since we are
discussing about ‘Spring Boot Annotations With Examples’, we need to at least have the basic idea of them.
Related
Tagged @Bean @bean annotation in spring boot @Bean vs @Component @Component @component in spring @component spring
boot @ComponentScan @Configuration @configuration vs
@component @Controller @EnableAutoConfiguration @EnableConfigurationProperties @EnableConfigurationPropertiesScan @EnableJpaReposito
annotations in spring boot all spring boot annotations all spring boot annotations list annotation in spring boot annotation on spring
boot annotation spring boot annotations in spring annotations in spring boot annotations in springboot annotations spring boot common
annotations in spring boot common spring boot annotations component annotation in spring enableglobalmethodsecurity important spring boot
annotations java spring list of annotations in spring boot list of spring boot annotations primary vs qualifier in spring boot spring and spring boot
annotations spring annotations spring annotations example spring annotations in java spring annotations list spring annotations tutorial spring
annotations with example spring annotations with examples spring boot all annotations spring boot all annotations list with explanation spring
boot annotation spring boot annotation in java spring boot annotations spring boot annotations and their uses spring boot annotations
example spring boot annotations explained Spring Boot Annotations explained with examples spring boot annotations interview questions spring
boot annotations list spring boot annotations list with examples spring boot annotations list with explanation spring boot annotations with
examples spring boot anotations spring boot application annotation spring boot specific annotations springboot annotation springboot
annotations springboot bean springbootapplication annotation stereotype annotations in spring what are the annotations used in spring
boot what are the spring boot annotations What is an Application Context in Spring Framework? what is annotation in spring boot What is The IoC
container?
Post navigation
Previous article
Spring Boot Bean Annotations With Examples
Next article
Java IDE Eclipse Keyboard Shortcuts
5. Meghdad Hajilou says:
January 22, 2022 at 8:52 PM