Online Wordpad
Online Wordpad
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.
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.
@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 {
}
@PropertySources (For Multiple Property Locations)
Of course, If we have multiple property locations in our project, we can also use
the @PropertySources annotation and specify an array of @PropertySource.
@Configuration
@PropertySources({
@PropertySource("classpath:/com/dev/javatechonline/app1.properties"),
@PropertySource("classpath:/com/dev/javatechonline/app2.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
Now inject the value of server.ip using @Value as below:
@Value("${server.ip}")
private String serverIP;
@Value for default Value
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.
@Value("${columnNames}")
private String[] columnNames;
Spring Boot Specific Annotations
Now it’s time to extend our topic ‘Spring Boot Annotations with Examples’ with
Spring Boot Specific Annotations. They are discovered by Spring Boot Framework
itself. However, most of them internally use annotations provided by Spring
Framework and extend them further.
@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.
@SpringBootConfiguration
public class MyApplication {
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;
@Configuration
@EnableConfigurationProperties(MyDevAppProperties.class)
public class MySpringBootDevApp { }
Finally create a Test Runner to test the values of properties as below.
@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());
}
}
We can also use the @ConfigurationProperties annotation on @Bean-annotated methods.
@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 { }
From the above example, @EnableConfigurationPropertiesScan will scan all the
@ConfiguratonProperties annotated classes under the package
“com.dev.spring.test.annotation” and register them accordingly.
@EntityScan(basePackages = "com.dev.springboot.examples.entity")
@EnableJpaRepositories(basePackages =
"com.dev.springboot.examples.jpa.repositories")
Links to Other Annotations
As stated in the introduction section of our article ‘Spring Boot Annotations With
Examples’, we will discuss all annotations that we generally use in a Spring Boot
web Application. Below are the links to continue with ‘Spring boot Annotations with
Examples’:
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.