Summary:
In this article, you will learn Spring Boot Annotations like
- @Bean
- @Service
- @Repository
- @Configuration
- @Controller
- @RequestMapping
- @Autowired
- @Component
- @SpringBootApplication
- @EnableAutoConfiguration
Read the full article to know more in detail.
Spring Boot Annotations are a form of metadata that provides data about a program that is not a part of the program itself. They do not have any direct effect on the operation of the code they annotate. Spring Boot Annotations do not use XML and instead use the convention over configuration principle. Check out our free courses to get an edge over the competition.
Spring Boot Annotations have certain advantages attached to them such as-
- Works well the servlet containers
- Saves memory space due to bootstrapping
- No requirement for WAR files
- POM dependency management
- XML configuration is not required
- Boilerplate code is decreased
In java spring boot, the servlet containers are the atmosphere where the Java web applications can survive/ live. Servlet COntainer or Web Container is the application server where it applies various Java versions like Java Servlet, JSP, etc.
Bootstrapping in spring boot annotations is nothing but a process of initialising an application. The application can be initialised by using the Spring Intialiser. Bootstrapping allows the users to utilise the space in their respective devices while they give the scope to applications to load quickly.
WAR files in software engineering stand for Web Application Resource or Web Application ARchive). Although spring boot can use WAR files they use JAR files for various reasons, such as the compressed file size which helps the developers to connect the applications with tools. Also, the JAR files are easier to handle, create, update, etc.
POM is Project – Object-Model, it contains the information about the project in the XML file. The POM dependency management is the centralised process to manage the dependency information. The Springboot dependencies allow the developers to manage dependencies without relying on the parent POM or XML file.
The developers can avoid the XML configuration in java spring boot, which appeals to the developers as it allows them to skip extra steps.
The boilerplate code is can be used by using the Spring Boot embedded server, as it decreases the boilerplate code. The absence of boilerplate code gives the developers a scope to lessen the time to develop applications and increase their productivity.
Also Spring boot starter is another feature, they are dependency descriptors. They can be added under the dependency section in pom. or xml.
Given below are some important Spring Boot Annotations.
Spring Boot Annotations Everyone Should Know
1. @Bean
The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be managed by the Spring container. It is an alternative to the XML<bean> tag.
Example:
@Bean
Public BeanExample beanExample ()
{
return new BeanExample (),
}
You can also consider doing our Java Bootcamp course from upGrad to upskill your career.
In the spring boot annotation, beans are the objects that are the backbone of the application and are managed by the Spring IoC container. The Spring Bean annotation is declared in the configuration classes method.
Explore Our Software Development Free Courses
2. @Service
It is used at the class level. It shows that the annotated class is a service class, such as business basic logic, and call external APIs.
Example:
@Service
public class TestService
{
public void service1()
{
// business code
}
}
The @service annotation is used where the classes provide some business functionalities. The spring context autodetects these classes as the annotation is used with those classes where the business functionalities are to be used.
Read: Spring Boot Projects & Topics
3. @Repository
It is a Data Access Object (DAO) that accesses the database directly. It indicates that the annotated class is a repository.
Example:
@Repository
public class TestRepository
{
public void delete()
{
// persistence code
}
}
The repository annotation indicates the class has the capability of storage, retrieval, updating, deletion, and search.
Featured Program for you: Fullstack Development Bootcamp Course
4. @Configuration
It is used as a source of bean definitions. It is a class-level annotation.
Example:
@Configuration
public class Bus
{
@BeanBus engine()
{
return new Bus();
}
}
The configuration annotation represents the class having one or more @Bean methods. The spring container could go ahead and generate the Spring Beans to be used.
Explore our Popular Software Engineering Courses
5. @Controller
The annotation is used to indicate that the class is a web request handler. It is often used to present web pages. It is most commonly used with @RequestMapping annotation.
Example:
@Controller
@RequestMapping(“cars”)
public class CarsController
{
@RequestMapping(value= “/{name}”, method= RequestMethod.GET)
public Employee getCarsByName()
{
Return carsTemplate;
}
}
The controller annotation indicates the class serves the role of a controller. The controller annotation is a specialisation of the component annotation where it is auto-detected through the classpath scanning.
In-Demand Software Development Skills
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
6. @RequestMapping
RequestMapping is used to map the HTTP request. It is used with the class as well as the method. It has many other optional elements like consumes, name, method, request, path, etc.
Example:
@Controller
public class FlowersController
{
@RequestMapping (“/red-colour/flowers”)
public String getAllFlowers(Model model)
{
//application code
return “flowerlist”;
}
Also visit upGrad’s Degree Counselling page for all undergraduate and postgraduate programs.
7. @Autowired
This annotation is used to auto-wire spring bean on setter methods, constructor and instance variable. It injects object dependency implicitly. When we use this annotation, the spring container auto-wires the bean by its matching data type.
Example:
@Component
public class Employee
private Person person;
@Autowired
public Employee(Person person)
{
this.person=person
}
}
The Autowired annotation is used to inject the dependency in the bean. The Autowired provides more control to the developers over where the Autowire should be used.
Also Read: Spring Developer Salary in India
8. @Component
It is a class-level annotation that turns the class into Spring bean at the auto-scan time.
Example:
@Component
Public class Teachers
{
……
}
The component annotation can automatically detect custom beans. It represents that the framework could autodetect these classes for dependency injection.
9. @SpringBootApplication
It consists of @Configuration, @ComponentScan, and @EnabeAutoConfiguration. The class annotated with @SpringBootApplication is kept in the base package. This annotation does the component scan. However, only the sub-packages are scanned.
The SpringBoot Application mark a configuration class that declares Bean methods, either one or more than that. The Spring Boot Application contains-
- Auto-configuration
- Spring Boot Configuration
- Component Scan
10. @EnableAutoConfiguration
It is placed on the main application class. Based on classpath settings, other beans, and various property settings, this annotation instructs SpringBoot to start adding beans.
The Enable Auto Configuration allows the spring boot to auto-figure the application context. The applications are auto figured basis the added jar dependencies.
11. @ComponetScan
It is used to scan a package of beans. It is used with the annotation @Configuration to allow Spring to know the packages to be scanned for annotated components. This annotation is also used to specify base packages.
Example:
@ComponentScan(basePackages = “com.xyz”)
@Configuration
Public class ScanComponent
{
//…
}
The component scan annotation specifies the packages the developers want to scan. The component scan annotations specify the packages and sub-packages that are supposed to be scanned.
12. @Required
This annotation is applied to bean setter methods. It indicates that the required property must be filled at the configuration time in the affected bean, or else it throws an exception: BeanInitializationException.
13. @Qualifier
It is used along with @Autowired annotation. It is used when more control is required over the dependency injection process. Individual constructor arguments or method parameters can be specified by using this annotation. Confusion arises when more than one bean of the same type is created, and only one of them is to be wired with a property, @Qualifier is used to get rid of the confusion.
14. @CookieValue
It is used at the method parameter level as an argument of the request mapping method. For a given cookie name, the HTTP cookie is bound to a @CookieValue parameter.
The cookie value annotation is used to get the value of any HTTP cookie. Cookies in spring boot are used to show the personalised content to the users and they can be retrieved using the cookie value annotation.
15. @Lazy
It is used in the component class. At startup, all auto-wired dependencies are created and configured. But a @Lazy annotation can be created if a bean is to be initialized lazily. This means that only if it is requested for a bean will be created. It can also be used on @Configuartion classes. It’s an indication that all @Bean methods within that @Configuration should be lazily initialized.
Check out: Spring Bean Life Cycle Explained
Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Read our Popular Articles related to Software Development
Conclusion
Spring Boot has made it easy for Java developers to create Spring applications with ease. As a Java enthusiast or a professional, you should be aware of the basic Spring boot annotations. We hope that this blog helped you understand them. You can take the first step towards a successful Java career by enrolling for upGrad and IIIT-B’s Executive PG Program in Full Stack Development.
Why are annotations used in Java?
Java annotations are the metadata, i.e. data about data, of the source code of the program. Annotations are used to supply extra information to the compiler about a Java program. However, these are not a part of the Java program and do not, in any way, influence the program execution. Java annotations start with @. For example, the @Override annotation is used to signal the compiler that the specified method marked with that annotation should override the method contained in the superclass with the same name, parameter list and return type. There are different kinds of formats for annotations used in Java.
What is the difference between Spring Boot and Spring Cloud?
Spring Boot is an open-source Java framework that is used to create microservices. On the other hand, Spring Cloud is a technology for configuration server that is used to centralize and manage configuration. Spring Cloud is also implemented to ensure the security of applications running on Spring Boot in many cases. By default, Spring Boot implements Spring features and can quickly execute standalone Spring web-based applications. Spring Cloud offers the platform to develop cloud services; its architecture is based on the Spring Boot model. Spring Boot is adopted for unit testing and reducing the time needed for integration testing.
What is Spring in Java?
Spring in Java is an open-source framework that offers the platform to develop Java applications. Programs written using Java are generally very complex and come with various components that make them heavyweight. Spring is a lightweight, low-cost and secure framework that offers the flexibility needed to develop complex programs and enhance the overall efficiency of execution. Spring also optimizes the overall time taken for developing Java applications and eliminates tedious tasks related to the configuration so that programmers can focus their attention on the business logic of applications. The core logic of the Spring framework is dependency injection that allows developers to create decoupled architecture. This framework facilitates the development of high-performing Java applications.