0% found this document useful (0 votes)
138 views20 pages

Public Class Customer (Private Person Person Private Int Type

The document discusses several Spring Framework annotations such as @Required, @Autowired, @Qualifier, @Configuration, and @Bean. It also covers Spring Boot annotations like @EnableAutoConfiguration and @SpringBootApplication. Finally, it summarizes Spring MVC and REST annotations including @Controller, @RequestMapping, @CookieValue, and @CrossOrigin that are commonly used to build web applications.

Uploaded by

mark kd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
138 views20 pages

Public Class Customer (Private Person Person Private Int Type

The document discusses several Spring Framework annotations such as @Required, @Autowired, @Qualifier, @Configuration, and @Bean. It also covers Spring Boot annotations like @EnableAutoConfiguration and @SpringBootApplication. Finally, it summarizes Spring MVC and REST annotations including @Controller, @RequestMapping, @CookieValue, and @CrossOrigin that are commonly used to build web applications.

Uploaded by

mark kd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

https://springframework.

guru/spring-framework-annotations/

https://www.w3schools.com/tags/ref_httpmethods.asp

 @Required

This annotation is applied on bean setter methods. Consider a scenario


where you need to enforce a required property.
The @Required annotation indicates that the affected bean must be
populated at configuration time with the required property. Otherwise
an exception of type BeanInitializationException is thrown.

 @Autowired

This annotation is applied on fields, setter methods, and constructors.


The @Autowired annotation injects object dependency implicitly.
When you use @Autowired on fields and pass the values for the fields
using the property name, Spring will automatically assign the fields
with the passed values.
You can even use @Autowired on private properties, as shown below.
(This is a very poor practice though!)
1. public class Customer {
2. @Autowired
3. private Person person;
4. private int type;
5. }
 

When you use @Autowired on setter methods, Spring tries to perform


the by Type autowiring on the method. You are instructing Spring that
it should initiate this property using setter method where you can add
your custom code, like initializing any other property with this
property.
1. public class Customer {
2. private Person person;
3. @Autowired
4. public void setPerson (Person person) {
5. this.person=person;
6. }
7. }
Consider a scenario where you need instance of class A, but you do not
store A in the field of the class. You just use A to obtain instance of B,
and you are storing B in this field. In this case setter method
autowiring will better suite you. You will not have class level unused
fields.
When you use @Autowired on a constructor, constructor injection
happens at the time of object creation. It indicates the constructor to
autowire when used as a bean. One thing to note here is that only one
constructor of any bean class can carry the @Autowired annotation.
1. @Component
2. public class Customer {
3. private Person person;
4. @Autowired
5. public Customer (Person person) {
6. this.person=person;
7. }
8. }
NOTE: As of Spring 4.3, @Autowired became optional on classes with
a single constructor. In the above example, Spring would still inject an
instance of the Person class if you omitted the @Autowired annotation.

@Qualifier

This annotation is used along with @Autowired annotation. When you


need more control of the dependency injection process, @Qualifier can
be used. @Qualifier can be specified on individual constructor
arguments or method parameters. This annotation is used to avoid
confusion which occurs when you create more than one bean of the
same type and want to wire only one of them with a property.
Consider an example where an interface BeanInterface is implemented
by two beans BeanB1 and BeanB2.
1. @Component
2. public class BeanB1 implements BeanInterface {
3. //
4. }
5. @Component
6. public class BeanB2 implements BeanInterface {
7. //
8. }
Now if BeanA autowires this interface, Spring will not know which
one of the two implementations to inject.
One solution to this problem is the use of the @Qualifier annotation.
1. @Component
2. public class BeanA {
3. @Autowired
4. @Qualifier("beanB2")
5. private BeanInterface dependency;
6. ...
7. }
With the @Qualifier annotation added, Spring will now know which
bean to autowire where beanB2 is the name of BeanB2.

 @Configuration

This annotation is used on classes which define


beans.  @Configuration  is an analog for XML configuration file – it is
configuration using Java class. Java class annotated
with  @Configuration  is a configuration by itself and will have
methods to instantiate and configure the dependencies.

 @Bean
This annotation is used at the method level. @Bean annotation works
with @Configuration to create Spring beans. As mentioned
earlier, @Configuration will have methods to instantiate and configure
dependencies. Such methods will be annotated with @Bean. The method
annotated with this annotation works as bean ID and it creates and
returns the actual bean.
Here is an example:

1. @Configuration
2. public class AppConfig{
3. @Bean
4. public Person person(){
5. return new Person(address());
6. }
7. @Bean
8. public Address address(){
9. return new Address();
10. }

 Spring Framework Stereotype Annotations


@Component

This annotation is used on classes to indicate a Spring component.


The  @Component  annotation marks the Java class as a bean or say
component so that the component-scanning mechanism of Spring can
add into the application context.

@Controller
The @Controller annotation is used to indicate the class is a Spring
controller. This annotation can be used to identify controllers for
Spring MVC or Spring WebFlux.

@Service

This annotation is used on a class. The  @Service  marks a Java class


that performs some service, such as execute business logic, perform
calculations and call external APIs. This annotation is a specialized
form of the  @Component  annotation intended to be used in the
service layer.

@Repository

This annotation is used on Java classes which directly access the


database. The  @Repository  annotation works as marker for any class
that fulfills the role of repository or Data Access Object.
This annotation has a automatic translation feature. For example,
when an exception occurs in the  @Repository  there is a handler for
that exception and there is no need to add a try catch block.

 Spring Boot Annotations


@EnableAutoConfiguration

This annotation is usually placed on the main application class.


The  @EnableAutoConfiguration  annotation implicitly defines a base
“search package”. This annotation tells Spring Boot to start adding
beans based on classpath settings, other beans, and various property
settings.
@SpringBootApplication

This annotation is used on the application class while setting up a


Spring Boot project. The class that is annotated with
the  @SpringBootApplication  must be kept in the base package. The
one thing that the  @SpringBootApplication  does is a component
scan. But it will scan only its sub-packages. As an example, if you put
the class annotated
with  @SpringBootApplication  in  com.example  then  @SpringBootA
pplication  will scan all its sub-packages, such
as  com.example.a ,  com.example.b , and  com.example.a.x .
he @SpringBootApplication is a convenient annotation that adds all
the following:

o @Configuration
o @EnableAutoConfiguration
o @ComponentScan

 Spring MVC and REST Annotations


@Controller

This annotation is used on Java classes that play the role of controller
in your application. The  @Controller  annotation allows autodetection
of component classes in the classpath and auto-registering bean
definitions for them. To enable autodetection of such annotated
controllers, you can add component scanning to your configuration.
The Java class annotated with  @Controller  is capable of handling
multiple request mappings.
This annotation can be used with Spring MVC and Spring WebFlux.

@RequestMapping

This annotation is used both at class and method level.


The  @RequestMapping  annotation is used to map web requests onto
specific handler classes and handler methods.
When  @RequestMapping  is used on class level it creates a base URI
for which the controller will be used. When this annotation is used on
methods it will give you the URI on which the handler methods will
be executed. From this you can infer that the class level request
mapping will remain the same whereas each handler method will have
their own request mapping.
Sometimes you may want to perform different operations based on the
HTTP method used, even though the request URI may remain the
same. In such situations, you can use the  method  attribute
of  @RequestMapping  with an HTTP method value to narrow down
the HTTP methods in order to invoke the methods of your class.
Here is a basic example on how a controller along with request
mappings work:

1. @Controller
2. @RequestMapping("/welcome")
3. public class WelcomeController{
4. @RequestMapping(method = RequestMethod.GET)
5. public String welcomeAll(){
6. return "welcome all";
7. }
8. }
In this example only  GET  requests to  /welcome  is handled by
the  welcomeAll()  method.
This annotation also can be used with Spring MVC and Spring
WebFlux.

The @RequestMapping annotation is very versatile. Please see my in


depth post on Request Mapping bere .

@CookieValue

This annotation is used at method parameter level.  @CookieValue  is


used as argument of request mapping method. The HTTP cookie is
bound to the  @CookieValue  parameter for a given cookie name. This
annotation is used in the method annotated with  @RequestMapping .
Let us consider that the following cookie value is received with a http
request:
JSESSIONID=418AB76CD83EF94U85YD34W
To get the value of the cookie, use  @CookieValue  like this:
1. @RequestMapping("/cookieValue")
2. public void getCookieValue(@CookieValue "JSESSIONID"
String cookie){
3. }

@CrossOrigin

This annotation is used both at class and method level to enable cross
origin requests. In many cases the host that serves JavaScript will be
different from the host that serves the data. In such a case Cross
Origin Resource Sharing (CORS) enables cross-domain
communication. To enable this communication you just need to add
the  @CrossOrigin  annotation.
By default the  @CrossOrigin  annotation allows all origin, all headers,
the HTTP methods specified in the  @RequestMapping  annotation
and  maxAge  of 30 min. You can customize the behavior by
specifying the corresponding attribute values.
An example to use @CrossOrigin at both controller and handler
method levels is this.

1. @CrossOrigin(maxAge = 3600)
2. @RestController
3. @RequestMapping("/account")
4. public class AccountController {
5.
6. @CrossOrigin(origins = "http://example.com")
7. @RequestMapping("/message")
8. public Message getMessage() {
9. // ...
10. }
11.
12. @RequestMapping("/note")
13. public Note getNote() {
14. // ...
15. }
16. }
In this example, both  getExample()  and  getNote()  methods will
have a  maxAge  of 3600 seconds. Also,  getExample()  will only
allow cross-origin requests from  http://example.com ,
while  getNote()  will allow cross-origin requests from all hosts.
Composed @RequestMapping Variants
Spring framework 4.3 introduced the following method-level variants
of  @RequestMapping  annotation to better express the semantics of
the annotated methods. Using these annotations have become the
standard ways of defining the endpoints. They act as wrapper
to  @RequestMapping.
These annotations can be used with Spring MVC and Spring
WebFlux.

@GetMapping

This annotation is used for mapping HTTP GET requests onto specific
handler methods.  @GetMapping  is a composed annotation that acts
as a shortcut for  @RequestMapping(method = RequestMethod.GET)

@PostMapping

This annotation is used for mapping HTTP POST requests onto


specific handler methods.  @PostMapping  is a composed annotation
that acts as a shortcut for  @RequestMapping(method =
RequestMethod.POST)

@PutMapping

This annotation is used for mapping HTTP PUT requests onto specific
handler methods.  @PutMapping  is a composed annotation that acts as
a shortcut for  @RequestMapping(method = RequestMethod.PUT)

@PatchMapping
This annotation is used for mapping HTTP PATCH requests onto
specific handler methods.  @PatchMapping  is a composed annotation
that acts as a shortcut for  @RequestMapping(method =
RequestMethod.PATCH)

@DeleteMapping

This annotation is used for mapping HTTP DELETE requests onto


specific handler methods.  @DeleteMapping  is a composed annotation
that acts as a shortcut for  @RequestMapping(method =
RequestMethod.DELETE)

@ExceptionHandler

This annotation is used at method levels to handle exception at the


controller level. The  @ExceptionHandler  annotation is used to define
the class of exception it will catch. You can use this annotation on
methods that should be invoked to handle an exception.
The  @ExceptionHandler  values can be set to an array of Exception
types. If an exception is thrown that matches one of the types in the
list, then the method annotated with
matching  @ExceptionHandler  will be invoked.

@InitBinder

This annotation is a method level annotation that plays the role of


identifying the methods which initialize the  WebDataBinder  -
a  DataBinder  that binds the request parameter to JavaBean objects.
To customise request parameter data binding , you can
use  @InitBinder  annotated methods within our controller. The
methods annotated with  @InitBinder  all argument types that handler
methods support.
The  @InitBinder  annotated methods will get called for each HTTP
request if you don’t specify the value element of this annotation. The
value element can be a single or multiple form names or request
parameters that the init binder method is applied to.

@Mappings and @Mapping

This annotation is used on fields. The  @Mapping  annotation is a


meta annotation that indicates a web mapping annotation. When
mapping different field names, you need to configure the source field
to its target field and to do that you have to add
the  @Mappings  annotation. This annotation accepts an array
of  @Mapping  having the source and the target fields.

@MatrixVariable

This annotation is used to annotate request handler method arguments


so that Spring can inject the relevant bits of matrix URI. Matrix
variables can appear on any segment each separated by a semicolon. If
a URL contains matrix variables, the request mapping pattern must
represent them with a URI template.
The  @MatrixVariable  annotation ensures that the request is matched
with the correct matrix variables of the URI.

@PathVariable

This annotation is used to annotate request handler method arguments.


The  @RequestMapping  annotation can be used to handle dynamic
changes in the URI where certain URI value acts as a parameter. You
can specify this parameter using a regular expression.
The  @PathVariable  annotation can be used declare this parameter.

@RequestAttribute

This annotation is used to bind the request attribute to a handler


method parameter. Spring retrieves the named attributes value to
populate the parameter annotated with  @RequestAttribute . While
the  @RequestParam  annotation is used bind the parameter values
from query string, the  @RequestAttribute  is used to access the
objects which have been populated on the server side.

@RequestBody

This annotation is used to annotate request handler method arguments.


The  @RequestBody  annotation indicates that a method parameter
should be bound to the value of the HTTP request body.
The  HttpMessageConveter  is responsible for converting from the
HTTP request message to object.
@RequestHeader

This annotation is used to annotate request handler method arguments.


The  @RequestHeader  annotation is used to map controller parameter
to request header value. When Spring maps the
request,  @RequestHeader  checks the header with the name specified
within the annotation and binds its value to the handler method
parameter. This annotation helps you to get the header details within
the controller class.

@RequestParam

This annotation is used to annotate request handler method arguments.


Sometimes you get the parameters in the request URL, mostly in GET
requests. In that case, along with the  @RequestMapping  annotation
you can use the  @RequestParam  annotation to retrieve the URL
parameter and map it to the method argument.
The  @RequestParam  annotation is used to bind request parameters to
a method parameter in your controller.

@RequestPart

This annotation is used to annotate request handler method arguments.


The  @RequestPart  annotation can be used instead
of  @RequestParam  to get the content of a specific multipart and bind
to the method argument annotated with  @RequestPart . This
annotation takes into consideration the “Content-Type” header in the
multipart(request part).

@ResponseBody

This annotation is used to annotate request handler methods.


The  @ResponseBody  annotation is similar to
the  @RequestBody  annotation. The  @ResponseBody  annotation
indicates that the result type should be written straight in the response
body in whatever format you specify like JSON or XML. Spring
converts the returned object into a response body by using
the  HttpMessageConveter .
@ResponseStatus

This annotation is used on methods and exception


classes.  @ResponseStatus  marks a method or exception class with a
status code and a reason that must be returned. When the handler
method is invoked the status code is set to the HTTP response which
overrides the status information provided by any other means. A
controller class can also be annotated with  @ResponseStatus  which is
then inherited by all  @RequestMapping  methods.

@ControllerAdvice

This annotation is applied at the class level. As explained earlier, for


each controller you can use  @ExceptionHandler  on a method that
will be called when a given exception occurs. But this handles only
those exception that occur within the controller in which it is defined.
To overcome this problem you can now use
the  @ControllerAdvice  annotation. This annotation is used to
define  @ExceptionHandler ,  @InitBinder  and  @ModelAttribute  met
hods that apply to all  @RequestMapping  methods. Thus if you define
the  @ExceptionHandler  annotation on a method
in  @ControllerAdvice  class, it will be applied to all the controllers.

@RestController

This annotation is used at the class level.


The  @RestController  annotation marks the class as a controller where
every method returns a domain object instead of a view. By annotating
a class with this annotation you no longer need to
add  @ResponseBody  to all the RequestMapping method. It means
that you no more use view-resolvers or send html in response. You
just send the domain object as HTTP response in the format that is
understood by the consumers like JSON.
@RestController  is a convenience annotation which
combines  @Controller  and  @ResponseBody .

@RestControllerAdvice

This annotation is applied on Java classes.  @RestControllerAdvice  is


a convenience annotation which
combines  @ControllerAdvice  and  @ResponseBody . This annotation
is used along with the  @ExceptionHandler  annotation to handle
exceptions that occur within the controller.
@SessionAttribute

This annotation is used at method parameter level.


The  @SessionAttribute  annotation is used to bind the method
parameter to a session attribute. This annotation provides a convenient
access to the existing or permanent session attributes.

@SessionAttributes

This annotation is applied at type level for a specific handler.


The  @SessionAtrributes  annotation is used when you want to add a
JavaBean object into a session. This is used when you want to keep
the object in session for short lived.  @SessionAttributes  is used in
conjunction with  @ModelAttribute .
Consider this example.
1. @ModelAttribute("person")
2. public Person getPerson(){}
3. // within the same controller as above snippet
4. @Controller
5. @SeesionAttributes(value="person", types={Person.class})
6. public class PersonController{}
The  @ModelAttribute  name is assigned to
the  @SessionAttributes  as value. The  @SessionAttributes  has two
elements. The value element is the name of the session in the model
and the types element is the type of session attributes in the model.

 Spring Cloud Annotations


@EnableConfigServer

This annotation is used at the class level. When developing a project


with a number of services, you need to have a centralized and
straightforward manner to configure and retrieve the configurations
about all the services that you are going to develop. One advantage of
using a centralized config server is that you don’t need to carry the
burden of remembering where each configuration is distributed across
multiple and distributed components.

You can use Spring cloud’s  @EnableConfigServer  annotation to start


a config server that the other applications can talk to.

@EnableEurekaServer

This annotation is applied to Java classes. One problem that you may
encounter while decomposing your application into microservices is
that, it becomes difficult for every service to know the address of
every other service it depends on. There comes the discovery service
which is responsible for tracking the locations of all other
microservices.
Netflix’s Eureka is an implementation of a discovery server and
integration is provided by Spring Boot. Spring Boot has made it easy
to design a Eureka Server by just annotating the entry class
with  @EnableEurekaServer .

@EnableDiscoveryClient

This annotation is applied to Java classes. In order to tell any


application to register itself with Eureka you just need to add
the  @EnableDiscoveryClient annotation to the application entry
point. The application that’s now registered with Eureka uses the
Spring Cloud Discovery Client abstraction to interrogate the registry
for its own host and port.
@EnableCircuitBreaker

This annotation is applied on Java classes that can act as the circuit
breaker. The circuit breaker pattern can allow a micro service continue
working when a related service fails, preventing the failure from
cascading. This also gives the failed service a time to recover.

The class annotated with  @EnableCircuitBreaker  will monitor, open,


and close the circuit breaker.

@HystrixCommand

This annotation is used at the method level. Netflix’s Hystrix library


provides the implementation of Circuit Breaker pattern. When you
apply the circuit breaker to a method, Hystrix watches for the failures
of the method. Once failures build up to a threshold, Hystrix opens the
circuit so that the subsequent calls also fail. Now Hystrix redirects
calls to the method and they are passed to the specified fallback
methods.
Hystrix looks for any method annotated with
the  @HystrixCommand  annotation and wraps it into a proxy
connected to a circuit breaker so that Hystrix can monitor it.
Consider the following example:

1. @Service
2. public class BookService{
3. private final RestTemplate restTemplate;
4. public BookService(RestTemplate rest){
5. this.restTemplate = rest;
6. }
7. @HystrixCommand(fallbackMethod = "newList") public String
bookList(){
8. URI uri = URI.create("http://localhost:8081/recommended");
return this.restTemplate.getForObject(uri, String.class);
9. }
10. public String newList(){
11. return "Cloud native Java";
12. }
13. }
Here  @HystrixCommand  is applied to the original
method  bookList() . The  @HystrixCommand  annotation has newList
as the fallback method. So for some reason if Hystrix opens the circuit
on  bookList() , you will have a placeholder book list ready for the
users.

You might also like