0% found this document useful (0 votes)
3 views

spring

The document provides a comprehensive overview of various annotations used in the Spring Framework and Spring Boot, detailing their purposes and usage. Key annotations include @Autowired for dependency injection, @Configuration for defining beans, and @SpringBootApplication as the main entry point for Spring Boot applications. It also covers annotations for RESTful services, aspect-oriented programming, and testing, along with examples for clarity.

Uploaded by

findurmilarai
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

spring

The document provides a comprehensive overview of various annotations used in the Spring Framework and Spring Boot, detailing their purposes and usage. Key annotations include @Autowired for dependency injection, @Configuration for defining beans, and @SpringBootApplication as the main entry point for Spring Boot applications. It also covers annotations for RESTful services, aspect-oriented programming, and testing, along with examples for clarity.

Uploaded by

findurmilarai
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Spring Framework Annotations

Sl.No Annotation Description


01. @Autowired Annotation @Autowired is used to inject object dependency
implicitly for a constructor, field or method. This is known as “autowired by type”
since the object to be injected is discovered by its type. The items declared
@Autowired need not have to be public.

@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired


annotation. It is used to autowire spring bean on setter methods, instance
variable, and constructor. When we use @Autowired annotation, the spring container
auto-wires the bean by matching data-type.

@Component
public class Customer
{
private Person person;

@Autowired
public Customer(Person person){
this.person=person;
}
}

02. @Configurable Used on classes to inject properties of domain objects.


Types whose properties are injected without being instantiated by Spring can be
declared with @Configurable annotation.
@Configuration: It is a class-level annotation. The class annotated with
@Configuration used by Spring Containers as a source of bean definitions.

@Configuration
public class Vehicle
{
@Bean
Vehicle engine() {
return new Vehicle();
}
}

03. @Qualifier It can be used to create more than one bean of the same type and
wire only one of the types with a property. It provides greater control on the
dependency injection process and can be used with @Autowired annotation.
04. @Required Used to mark class members that are mandatory. The Spring auto-
configuration fails if a particular property specified with this annotation cannot
be injected.
@Required: It applies to the bean setter method. It indicates that the annotated
bean must be populated at configuration time with the required property, else it
throws an exception BeanInitilizationException.
public class Machine
{
private Integer cost;

@Required
public void setCost(Integer cost) {
this.cost = cost;
}

public Integer getCost()


{ return cost; }
}

05. @ComponentScan Make Spring scan the package for the @Configuration clases.

@ComponentScan: It is used when we want to scan a package for beans. It is used


with the annotation @Configuration. We can also specify the base packages to scan
for Spring Components.

@ComponentScan(basePackages = "com.javatpoint")
@Configuration
public class ScanComponent
{
// ...
}

06. @Configuration It is used on classes that define beans.

07. @Bean It indicates that a method produces a bean which will be mananged by
the Spring container.
08. @Lazy Makes a @Bean or @Component to be initialized only if it is requested.
09. @Value It is used to inject values into a bean’s attribute from a
property file. @Value annotation indicates a default value expression for the field
or parameter.
10. @Resource Annotation used to inject an object that is already in the Appl-
ication Context. It searches the instance by name. It also works on setter methods.
11. @Primary Annotation used when no name is provided telling Spring to inject
an object of the annotated class first. Used along with @Component.
12. @Component Generic stereotype annotation used to tell Spring to create an
instance of the object in the Application Context. It’s possible to define any name
for the instance, the default is the class name as camel case.

@Component: It is a class-level annotation. It is used to mark a Java class as a


bean.
A Java class annotated with @Component is found during the classpath.
The Spring Framework pick it up and configure it in the application context as a
Spring Bean.

@Component
public class Student
{
.......
}
13. @Controller Stereotype annotation for presentation layer.

@Controller: The @Controller is a class-level annotation. It is a specialization of


@Component. It marks a class as a web request handler. It is often used to serve
web pages. By default, it returns a string that indicates which route to redirect.
It is mostly used with @RequestMapping annotation.

@Controller
@RequestMapping("books")
public class BooksController
{
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public Employee getBooksByName()
{
return booksTemplate;
}
}
14. @Repository Stereotype annotation for persistence layer.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access
Object) that access the database directly. The repository does all the operations
related to the database.

package com.javatpoint;
@Repository
public class TestRepository
{
public void delete()
{
//persistence code
}
}

15. @Service Stereotype annotation for service layer.


@Service: It is also used at class level. It tells the Spring that class contains
the business logic.

package com.javatpoint;
@Service
public class TestService
{
public void service1()
{
//business code
}
}

Spring-Boot Web Annotations


Sl.No Annotation Description
01. @SpringBootApplication This annotation is used to qualify the main class for
a Spring Boot project. The class used with this annotation must be present in the
base path. @SpringBootApplication scans for sub-packages by doing a component scan.
02. @EnableAutoConfiguration Based on class path settings, property
settings, new beans are added by Spring Boot by using this annotation.
03. @Controller Allows detection of component classes in the class path
automatically and register bean definitions for the classes automatically.
04. @RestController Used in controllers that will behave as RESTful resources.
@RestController is a convenience annotation that combines @Controller and
@ResponseBody.
05. @ResponseBody Makes Spring to convert the returned object to a response
body. This is useful for classes exposed as RESTful resources.
06. @RequestMapping Used to map web requests to specific handler classes and
methods, based on the URI.
07. @RequestParam This annotation is used to bind request parameters to a
method parameter in your controller.
08. @PathVariable This annotations binds the placeholder from the URI to the
method parameter and can be used when the URI is dynamically created or the value
of the URI itself acts as a parameter.
Profile
Sl.No Annotation Description
01. spring.profiles.active Property to be set in application.properties in order
to tell Spring what profiles are active.
02. @Profile(“dev”) Annotation used to define which profile can execute the
annotated method.

Spring MVC and REST Annotations


@RequestMapping: It is used to map the web requests. It has many optional elements
like consumes, header, method, name, params, path, produces, and value. We use it
with the class as well as the method.
Example

@Controller
public class BooksController
{
@RequestMapping("/computer-science/books")
public String getAllBooks(Model model)
{
//application code
return "bookList";
}
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is
used to create a web service endpoint that fetches It is used instead of using:
@RequestMapping(method = RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is
used to create a web service endpoint that creates It is used instead of using:
@RequestMapping(method = RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is
used to create a web service endpoint that creates or updates It is used instead of
using:
@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It
is used to create a web service endpoint that deletes a resource. It is used
instead of using:
@RequestMapping(method = RequestMethod.DELETE)
@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It
is used instead of using:
@RequestMapping(method = RequestMethod.PATCH)
@RequestBody: It is used to bind HTTP request with an object in a method parameter.
Internally it uses HTTP MessageConverters to convert the body of the request. When
we annotate a method parameter with
@RequestBody, the Spring framework binds the incoming HTTP request body to that
parameter.
@ResponseBody: It binds the method return value to the response body. It tells the
Spring Boot Framework to serialize a return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable
for the RESTful web service, where the URL contains a path variable. We can define
multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also
known as a query parameter. It is most suitable for web applications. It can
specify default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We
use this annotation as a method parameter. The optional elements of the annotation
are name, required, value, defaultValue. For each detail in the header, we should
specify separate annotations. We can use it multiple time in a method
@RestController: It can be considered as a combination of @Controller and
@ResponseBody annotations. The @RestController annotation is itself annotated with
the @ResponseBody annotation. It eliminates the need for annotating each method
with @ResponseBody.
@RequestAttribute: It binds a method parameter to request attribute. It provides
convenient access to the request attributes from a controller method. With the help
of @RequestAttribute annotation, we can access objects that are populated on the
server-side.

Aspect Annotations
Sl.No Annotation USE Description
01. @Aspect Type Declares a class to be an aspect.
02. @After Method Declares a method to be called after a pointcut
completes.
03. @AfterReturning Method Declares a method to be called after a pointcut
returns successfully.
04. @AfterThrowing Method Declares a method to be called after a pointcut
throws an exception.
05. @Around Method Declares a method that will wrap the pointcut.
06. @Before Method Declares a method to be called before proceeding to
the pointcut.
07. @DeclareParents Static Field Declares that matching types should be
given new parents,that is, it introduces new functionality into matching types.
08. @Pointcut Method Declares an empty method as a pointcut placeholder
method.

Spring-Boot Testing Annotations


Sl.No Annotation Description
01. @AfterTransaction Annotation used to identify which method needs to be
invoked after a transaction is completed.
02. @BeforeTransaction Used to identify the method to be invoked before a
transaction starts executing.
03. @ContextConfiguration Declares the annotated classes which will be used to
load the context for the test. The location of the configuration file has to be
povided to Spring.
04. @DirtiesContext This annotation indicates the test(s) modify or corrupt the
SpringApplicationContext and that it should be closed. Hence, context is reloaded
before the next test is executed.
05. @ExpectedException The test method is expected to throw a particular
exception, else the test fails.
06. @WebAppConfiguration Used to create web version of the application
context.
07. @Repeat Specifies the test method to be executed multiple times.
08. @Transactional Describes transaction attributes on a method or class.
09. @Rollback Indicates if the transaction of a test method must be rolled back
after the execution of the test completed.
10. @Commit Indicates that the transaction of a test method must be committed
after the execution of the test completed.
11. @Timed Indicates the time limit for the test method. If the test has not
completed execution before the time expires, the test fails.
12. @TestPropertySource Annotation specifies the property sources for the
test class.
13. @Sql Annotation declares a test class/method to run SQL scripts against a
database.

@SpringBootApplication
This application is the combination of so many different annotations which
includes:

@Configuration
@ComponentScan
@EnableAutoConfiguration
This annotation is used in the main class of our application it is the entry point
of our application as well.

Example:

@SpringBootApplication
class SpringBootDemo {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemo.class, args);
}
}

@EnableAutoConfiguration
This annotation is used to enable auto-configuration in our application. If a class
contains this annotation then spring boot automatically looks for all beans on the
classpath and automatically configures them.

Can you tell how to exclude any package without using the basePackages filter?
We can use the exclude attribute while using the annotation @SpringBootApplication
as follows:

@SpringBootApplication(exclude= {Student.class})
public class InterviewBitAppConfiguration {}
24. How to disable specific auto-configuration class?
You can use the exclude attribute of @EnableAutoConfiguration for this purpose as
shown below:
@EnableAutoConfiguration(exclude = {InterviewBitAutoConfiguration.class})
If the class is not specified on the classpath, we can specify the fully qualified
name as the value for the excludeName.

//By using "excludeName"


@EnableAutoConfiguration(excludeName={Foo.class})
@Configuration
@EnableAutoConfiguration
class DemoConfigure {}

Auto-Configuration Conditions
We have different conditions for auto configurations. So when we write our own or
we can say custom configuration but we want spring to use them on some condition so
in order to achieve this we can use this condition annotation.

@ConditionalOnMissingClass and @ConditionalOnClass: Now we can pass the class


object as an argument in the annotation. Spring will only use this auto-
configuration bean if we pass the argument in the annotation.
Example:

@Configuration
@ConditionalOnClass(DataSource.class)
class SqlConnectionDemo {
//...
}

@ConditionalOnMissingBean and @ConditionalOnBean: We can also apply condition on


the presence or absence of a bean, which means we can pass the name of the bean
inside the annotations.
Example:

@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// ...
}

@ConditionalOnProperty: We can also apply conditions on the value. So by using this


annotation, we can be able to do so.
Example:

@Bean
@ConditionalOnProperty(
name = "username",
havingValue = "some-value"
)
DataSource dataSource() {
// ...
}

@ConditionalOnResource: We can also apply conditions by checking if the resource is


available or not.
Example:

@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
// ...
}

@ConditionalOnNotWebApplication and @ConditionalOnWebApplication: We can also apply


conditions on the application level we can apply them on checking whether they are
web application or not.
Example:
@ConditionalOnWebApplication
HealthDemoController healthDemoController() {
// ...
}

@ConditionalExpression: We use this annotation condition related to SQEL


expression. This condition comes under complex conditions.
Example:

@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
// ...
}

@Conditional: If you want to create some more and more complex conditions then we
can create a class which will turn to evaluate the custom condition.
Example:

@Conditional(HibernateCondition.class)
Properties additionalProperties() {
//...

@RequestMapping with @RequestParam


The @RequestParam annotation is used with @RequestMapping to bind a web request
parameter to the parameter of the handler method.

The @RequestParam annotation can be used with or without a value. The value
specifies the request param that needs to be mapped to the handler method
parameter, as shown in this code snippet.

@RestController
@RequestMapping("/home")
public class IndexController {

@RequestMapping(value = "/id")
String getIdByValue(@RequestParam("id") String personId){
System.out.println("ID is "+personId);
return "Get ID from query string of URL with value element";
}
@RequestMapping(value = "/personId")
String getId(@RequestParam String personId){
System.out.println("ID is "+personId);
return "Get ID from query string of URL without value element";
}
}
In Line 6 of this code, the request param id will be mapped to the personId
parameter personId of the getIdByValue() handler method.

An example URL is this:


localhost:8090/home/id?id=5
The value element of @RequestParam can be omitted if the request param and handler
method parameter names are same, as shown in Line 11.

An example URL is this:


localhost:8090/home/personId?personId=5
The required element of @RequestParam defines whether the parameter value is
required or not.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", required = false) String
personName){
return "Required element of request param";
}
}
In this code snippet, as the required element is specified as false, the getName()
handler method will be called for both of these URLs:

/home/name?person=xyz
/home/name
The default value of the @RequestParam is used to provide a default value when the
request param is not provided or is empty.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String
personName ){
return "Required element of request param";
}
}
In this code, if the person request param is empty in a request, the getName()
handler method will receive the default value John as its parameter.

Using @RequestMapping with HTTP Method


The Spring MVC @RequestMapping annotation is capable of handling HTTP request
methods, such as GET, PUT, POST, DELETE, and PATCH.

By default all requests are assumed to be of HTTP GET type.

In order to define a request mapping with a specific HTTP method, you need to
declare the HTTP method in @RequestMapping using the method element as follows.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
String get(){
return "Hello from get";
}
@RequestMapping(method = RequestMethod.DELETE)
String delete(){
return "Hello from delete";
}
@RequestMapping(method = RequestMethod.POST)
String post(){
return "Hello from post";
}
@RequestMapping(method = RequestMethod.PUT)
String put(){
return "Hello from put";
}
@RequestMapping(method = RequestMethod.PATCH)
String patch(){
return "Hello from patch";
}
}
In the code snippet above, the method element of the @RequestMapping annotations
indicates the HTTP method type of the HTTP request.

All the handler methods will handle requests coming to the same URL ( /home), but
will depend on the HTTP method being used.

For example, a POST request to /home will be handled by the post() method. While a
DELETE request to /home will be handled by the delete() method.

You can see how Spring MVC will map the other methods using this same logic.

Using @RequestMapping with Producible and Consumable


The request mapping types can be narrowed down using the produces and consumes
elements of the @RequestMapping annotation.

In order to produce the object in the requested media type, you use the produces
element of @RequestMapping in combination with the @ResponseBody annotation.

You can also consume the object with the requested media type using the consumes
element of @RequestMapping in combination with the @RequestBody annotation.

The code to use producible and consumable with @RequestMapping is this.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/prod", produces = {"application/JSON"})
@ResponseBody
String getProduces(){
return "Produces attribute";
}
@RequestMapping(value = "/cons", consumes = {"application/JSON",
"application/XML"})
String getConsumes(){
return "Consumes attribute";
}
}
In this code, the getProduces() handler method produces a JSON response. The
getConsumes() handler method consumes JSON as well as XML present in requests.

@RequestMapping with Headers


The @RequestMapping annotation provides a header element to narrow down the request
mapping based on headers present in the request.

You can specify the header element as myHeader = myValue.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {"content-type=text/plain"})
String post(){
return "Mapping applied along with headers";
}
}
In the above code snippet, the headers attribute of the @RequestMapping annotation
narrows down the mapping to the post() method. With this, the post() method will
handle requests to /home/head whose content-type header specifies plain text as the
value.

You can also indicate multiple header values like this:

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {"content-type=text/plain", "content-
type=text/html"}) String post(){
return "Mapping applied along with headers";
}
}
Here it implies that both text/plain as well as text/html are accepted by the
post() handler method.

@RequestMapping with Request Parameters


The params element of the @RequestMapping annotation further helps to narrow down
request mapping. Using the params element, you can have multiple handler methods
handling requests to the same URL, but with different parameters.

You can define params as myParams = myValue. You can also use the negation operator
to specify that a particular parameter value is not supported in the request.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch", params = {"personId=10"})
String getParams(@RequestParam("personId") String id){
return "Fetched parameter using params attribute = "+id;
}
@RequestMapping(value = "/fetch", params = {"personId=20"})
String getParamsDifferent(@RequestParam("personId") String id){
return "Fetched parameter using params attribute = "+id;
}
}
In this code snippet, both the getParams() and getParamsDifferent() methods will
handle requests coming to the same URL ( /home/fetch) but will execute depending on
the params element.

For example, when the URL is /home/fetch?id=10 the getParams() handler method will
be executed with the id value 10.. For the URL, localhost:8080/home/fetch?
personId=20, the getParamsDifferent() handler method gets executed with the id
value 20.

Using @RequestMapping with Dynamic URIs


The @RequestMapping annotation is used in combination with the @PathVaraible
annotation to handle dynamic URIs. In this use case, the URI values can act as the
parameter of the handler methods in the controller. You can also use regular
expressions to only accept the dynamic URI values that match the regular
expression.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)
String getDynamicUriValue(@PathVariable String id){
System.out.println("ID is "+id);
return "Dynamic URI parameter fetched";
}
@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)
String getDynamicUriValueRegex(@PathVariable("name") String name){
System.out.println("Name is "+name);
return "Dynamic URI parameter fetched using regex";
}
}
In this code, the method getDynamicUriValue() will execute for a request to
localhost:8080/home/fetch/10. Also, the id parameter of the getDynamicUriValue()
handler method will be populated with the value 10 dynamically.

The method getDynamicUriValueRegex() will execute for a request to


localhost:8080/home/fetch/category/shirt. However, an exception will be thrown for
a request to/home/fetch/10/shirt as it does not match the regular expression.

@PathVariable works differently from @RequestParam. You use @RequestParam to obtain


the values of the query parameters from the URI. On the other hand, you use
@PathVariable to obtain the parameter values from the URI template.

The @RequestMapping Default Handler Method


In the controller class you can have default handler method that gets executed when
there is a request for a default URI.

Here is an example of a default handler method.

@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping()
String default(){
return "This is a default method for the class";
}
}
In this code, A request to /home will be handled by the default() method as the
annotation does not specify any value.

@RequestMapping Shortcuts
Spring 4.3 introduced method-level variants, also known as composed annotations of
@RequestMapping. The composed annotations better express the semantics of the
annotated methods. They act as wrapper to @RequestMapping and have become the
standard ways of defining the endpoints.

For example, @GetMapping is a composed annotation that acts as a shortcut for


@RequestMapping(method = RequestMethod.GET).
The method level variants are:

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
The following code shows using the composed annotations.

@RestController
@RequestMapping("/home")
public class IndexController {
@GetMapping("/person")
public @ResponseBody ResponseEntity<String> getPerson() {
return new ResponseEntity<String>("Response from GET", HttpStatus.OK);
}
@GetMapping("/person/{id}")
public @ResponseBody ResponseEntity<String> getPersonById(@PathVariable String
id){
return new ResponseEntity<String>("Response from GET with id "
+id,HttpStatus.OK); }
@PostMapping("/person")
public @ResponseBody ResponseEntity<String> postPerson() {
return new ResponseEntity<String>("Response from POST method", HttpStatus.OK);
}
@PutMapping("/person")
public @ResponseBody ResponseEntity<String> putPerson() {
return new ResponseEntity<String>("Response from PUT method", HttpStatus.OK);
}
@DeleteMapping("/person")
public @ResponseBody ResponseEntity<String> deletePerson() {
return new ResponseEntity<String>("Response from DELETE method",
HttpStatus.OK);
}
@PatchMapping("/person")
public @ResponseBody ResponseEntity<String> patchPerson() {
return new ResponseEntity<String>("Response from PATCH method", HttpStatus.OK);
}
}
In this code, each of the handler methods are annotated with the composed variants
of @RequestMapping. Although, each variant can be interchangeably used with
@RequestMapping with the method attribute, it’s considered a best practice to use
the composed variant. Primarily because the composed annotations reduce the
configuration metadata on the application side and the code is more readable.

ResponseEntity
ResponseEntity represents the whole HTTP response: status code, headers, and body.
As a result, we can use it to fully configure the HTTP response.

If we want to use it, we have to return it from the endpoint; Spring takes care of
the rest.

ResponseEntity is a generic type. Consequently, we can use any type as the response
body:

Since we specify the response status programmatically, we can return with different
status codes for different scenarios:

@GetMapping("/age")
ResponseEntity<String> age(
@RequestParam("yearOfBirth") int yearOfBirth) {

if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>(
"Year of birth cannot be in the future",
HttpStatus.BAD_REQUEST);
}

return new ResponseEntity<>(


"Your age is " + calculateAge(yearOfBirth),
HttpStatus.OK);
}
Additionally, we can set HTTP headers:
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");

return new ResponseEntity<>(


"Custom header set", headers, HttpStatus.OK);
}

@RestController
@RequestMapping(value = "/webapi")
public class EmployeeResource {

@Autowired
private EmployeeRepo employeeRepo;

@RequestMapping(method = RequestMethod.GET, value = "/employees")


public List<Employee> getAllEmployees() {

return employeeRepo.findAll();
}

@RequestMapping(method = RequestMethod.POST, value = "/addemployee")


public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee) {
employeeRepo.save(employee);
System.out.println(employee);
return new ResponseEntity<Employee>(employee, HttpStatus.CREATED);
}

@RequestMapping(method = RequestMethod.GET, value =


"/employees/{employeeId}")
public ResponseEntity<Object> getEmployee(@PathVariable String employeeId) {

Optional<Employee> employee = employeeRepo.findById(employeeId);

if (employeeRepo.findById(employeeId).isEmpty()) {
return
ResponseEntity.status(HttpStatus.NO_CONTENT).body(employee);
} else {
return ResponseEntity.status(HttpStatus.OK).body(employee);

@RequestMapping(method = RequestMethod.DELETE, value =


"/deleteemployee/{employeeId}")
public String deleteEmployee(@PathVariable String employeeId) {

employeeRepo.deleteById(employeeId);
return "Record Deleted : " + employeeId;

@RequestMapping(method = RequestMethod.PUT, value = "/updateemployee")


public ResponseEntity<Object> updateemployee(@RequestBody Employee employee)
{
if (employeeRepo.existsById(employee.getEmployeeId())) {
employeeRepo.save(employee);
return ResponseEntity.status(HttpStatus.ACCEPTED).body(employee);
} else {

return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(employee);
}

JPA

package com.example.accessingdatajpa;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;

protected Customer() {}

public Customer(String firstName, String lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}

public Long getId() {


return id;
}

public String getFirstName() {


return firstName;
}

public String getLastName() {


return lastName;
}
}
Repositry
package com.example.accessingdatajpa;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

List<Customer> findByLastName(String lastName);

Customer findById(long id);


}

JPA Data with REST

package com.example.accessingdatarest;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String firstName;


private String lastName;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}
}

package com.example.accessingdatarest;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")


public interface PersonRepository extends PagingAndSortingRepository<Person, Long>
{

List<Person> findByLastName(@Param("name") String name);

Can we change the default port of the embedded Tomcat server in Spring boot?
Yes, we can change it by using the application properties file by adding a property
of server.port and assigning it to any port you wish to.
For example, if you want the port to be 8081, then you have to mention
server.port=8081. Once the port number is mentioned, the application properties
file will be automatically loaded by Spring Boot and the specified configurations
will be applied to the application.

What are the uses of @RequestMapping and @RestController annotations in Spring


Boot?
@RequestMapping:
This provides the routing information and informs Spring that any HTTP request
matching the URL must be mapped to the respective method.
org.springframework.web.bind.annotation.RequestMapping has to be imported to use
this annotation.
@RestController:
This is applied to a class to mark it as a request handler thereby creating RESTful
web services using Spring MVC. This annotation adds the @ResponseBody and
@Controller annotation to the class.
org.springframework.web.bind.annotation.RestController has to be imported to use
this annotation.

What is an advice? Explain its types in spring.


An advice is the implementation of cross-cutting concerns can be applied to other
modules of the spring application. Advices are of mainly 5 types:

Before:
This advice executes before a join point, but it does not have the ability to
prevent execution flow from proceeding to the join point (unless it throws an
exception).
To use this, use @Before annotation.
AfterReturning:
This advice is to be executed after a join point completes normally i.e if a method
returns without throwing an exception.
To use this, use @AfterReturning annotation.
AfterThrowing:
This advice is to be executed if a method exits by throwing an exception.
To use this, use @AfterThrowing annotation.
After:
This advice is to be executed regardless of the means by which a join point exits
(normal return or exception encounter).
To use this, use @After annotation.
Around:
This is the most powerful advice surrounds a join point such as a method
invocation.
To use this, use @Around annotation

What is the role of @ModelAttribute annotation?


The annotation plays a very important role in binding method parameters to the
respective attribute that corresponds to a model. Then it reflects the same on the
presentation page. The role of the annotation also depends on what the developer is
using that for. In case, it is used at the method level, then that method is
responsible for adding attributes to it. When used at a parameter level, it
represents that the parameter value is meant to be retrieved from the model layer.

47. What is the importance of the web.xml in Spring MVC?


web.xml is also known as the Deployment Descriptor which has definitions of the
servlets and their mappings, filters, and lifecycle listeners. It is also used for
configuring the ContextLoaderListener. Whenever the application is deployed, a
ContextLoaderListener instance is created by Servlet container which leads to a
load of WebApplicationC

What is the role of IOC container in spring?


IOC container is responsible to:

create the instance


configure the instance, and
assemble the dependencies

What are the types of IOC container in spring?


There are two types of IOC containers in spring framework.

BeanFactory
ApplicationContext

What is the difference between BeanFactory and ApplicationContext?


BeanFactory is the basic container whereas ApplicationContext is the advanced
container. ApplicationContext extends the BeanFactory interface. ApplicationContext
provides more facilities than BeanFactory such as integration with spring AOP,
message resource handling for i18n etc.

Question: Define Mono and Flux types?


Answer: Mono and Flux types, are both the reactor of the Spring Framework 5. The
Mono represents the single async value, while the Flux represents the stream of
async value. Together they help to implement the publisher interface, which is
defined clearly in the reactive streams specifications.

Question: What is the basic difference between Mono and Flux in Spring?
Answer: Mono implements the publisher and returns 0 or even one element while the
Flux implements the publisher and return N elements.

Question: What are the common features of Mono and Flux?


Answer: The common features of Mono and Flux include the following.

They represent streams.


They can’t be executed without consuming the stream using the subscribe method.
They are immutable and can be called again and again to create a new instance of
Flux or Mono.

What is the use of @Qualifier annotation?


Answer: It is mainly used when the developer is bound to create many beans of the
same type and want to wire only one of them with the property, in this scenario
@Qualifier with @Autowired is used for removing confusion and specifying the exact
bean to be wired.

Q) How is an event handled in Spring?

Answer: Event handling is achieved through the ApplicationEvent class and


ApplicationListner interface.

When the bean implements ApplicationListner then ApplicationEvent gets generated to


ApplicationContext and notifies that the bean is generated.

Q) What are the examples of standard Spring Events?

Answer: There are many standard Spring events serving respective purpose and few
among them are ContextStartedEvent, ContextRefreshedEvent, ContextStoppedEvent,
ContextClosedEvent, RequestHandledEvent etc.

Explain the bean scopes supported by Spring?


There are five scoped provided by the Spring Framework supports following five
scopes:

In singleton scope, Spring scopes the bean definition to a single instance per
Spring IoC container.
In prototype scope, a single bean definition has any number of object instances.
In request scope, a bean is defined as an HTTP request. This scope is valid only in
a web-aware Spring ApplicationContext.
In session scope, a bean definition is scoped to an HTTP session. This scope is
also valid only in a web-aware Spring ApplicationContext.
In the global-session scope, a bean definition is scoped to a global HTTP session.
This is also a case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is Singleton.

27. Are Singleton beans thread safe in Spring Framework?


No, singleton beans are not thread-safe in the Spring framework.

Explain the Bean lifecycle in the Spring framework?


The spring container finds the bean’s definition from the XML file and instantiates
the bean.
Spring populates all of the properties as specified in the bean definition (DI).
If the bean implementsBeanNameAware interface, spring passes the bean’s id to
setBeanName()
If Bean implementsBeanFactoryAware interface, spring passes the bean factory to
setBeanFactory()
If there are any beanBeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization()
If the bean implementsIntializingBean, its afterPropertySet() method is called. If
the bean has an init method declaration, the specified initialization method is
called.
If there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.
If the bean implementsDisposableBean, it will call the destroy()
29. Which are the important beans lifecycle methods? Can you override them?
There are two important bean lifecycle methods are:

The first one is set up which is called when the bean is loaded into the container.
The second method is the teardown method which is called when the bean is unloaded
from the container.
The bean tag has two important attributes (init-method and destroy-method) with
which you can define your own custom initialization and destroy methods. There are
also the corresponding annotations(@PostConstruct and @PreDestroy).

Explain different modes of auto wiring?


The autowiring functionality has five modes that can be used to instruct Spring
container to use autowiring for dependency injection:

no: This is the default setting. An explicit bean reference should be used for
wiring.
byName: When auto-wiring byName, the Spring container looks at the properties of
the beans on which the auto-wire attribute is set to byName in the XML
configuration file. It then tries to match and wire its properties with the beans
defined by the same names in the configuration file.
byType: When autowiring by datatype, the Spring container looks at the properties
of the beans on which auto-wire attribute is set to byType in the XML configuration
file. It then tries to match and wire a property if its type matches with exactly
one of the names of the bean in the configuration file. If more than one such beans
exist, a fatal exception is thrown.
constructor: This mode is similar to byType, but type applies to constructor
arguments. If there is not exactly one bean of the constructor argument type in the
container, a fatal error is raised.
autodetect: Spring first tries to wire using auto-wire by the constructor, if it
does not work, Spring tries to auto-wire by type.

What are benefits of using Spring?


Answer:
Following is the list of few of the great benefits of using Spring Framework:

Lightweight − Spring is lightweight when it comes to size and transparency. The


basic version of spring framework is around 2MB.
Inversion of control (IOC) − Loose coupling is achieved in spring using the
technique Inversion of Control. The objects give their dependencies instead of
creating or looking for dependent objects.
Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables
cohesive development by separating application business logic from system services.
Container − Spring contains and manages the life cycle and configuration of
application objects.
MVC Framework − Spring's web framework is a well-designed web MVC framework, which
provides a great alternative to web frameworks such as Struts or other over-
engineered or less popular web frameworks.
Transaction Management − Spring provides a consistent transaction management
interface that can scale down to a local transaction (using a single database, for
example) and scale up to global transactions (using JTA, for example).
Exception Handling − Spring provides a convenient API to translate technology-
specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into
consistent, unchecked exceptions

You might also like