Annotations
Annotations
Annotations
Java Annotations
• Annotations start with ‘@’.
• Provide supplemental information about a program.
• Attached with class, interface, methods or fields to indicate some
additional information which can be used by java compiler and JVM.
• Provide additional information, so it is an alternative option for XML
• Annotations do not change the action of a compiled program.
Hierarchy of Annotations in Java
Built-In Java Annotations
• Built-In Java Annotations used in Java code
• @Override
• @SuppressWarnings
• @Deprecated
• Built-In Java Annotations used in other annotations
• @Target
• @Retention
• @Inherited
• @Documented
@Override
Assures that the subclass method is overriding the parent class method.
class Base
{ public void Display()
{
System.out.println("Base display()");
}
public static void main(String args[])
{
Base t1 = new Derived();
t1.Display();
}
}
class Derived extends Base
{
@Override
public void Display()
{
System.out.println("Derived display()");
}
}
@SuppressWarnings
• It is used to inform the compiler to suppress specified compiler warnings.
• The warnings to suppress are specified by name, in string form.
• This type of annotation can be applied to any type of declaration.
class DeprecatedTest
{
@Deprecated
public void Display() { }
}
public class SuppressWarningTest
{
@SuppressWarnings({"checked", "deprecation"})
public static void main(String args[])
{
DeprecatedTest d1 = new DeprecatedTest();
d1.Display();
}
}
If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile
time because we are using non-generic collection.
@Deprecated
• Marks that this method is deprecated so compiler prints warning. It informs user that it may be removed in the future
versions. So, it is better not to use such methods.
public class DeprecatedTest
{
@Deprecated
public void Display()
{
System.out.println("Deprecatedtest display()");
}
public static void main(String args[])
{
DeprecatedTest d1 = new DeprecatedTest();
d1.Display();
}
}
User-defined (Custom)
• User-defined annotations can be used to annotate • AnnotationName is an interface.
program elements, i.e. variables, constructors,
methods, etc.
• Parameters will not have a null value but can have a
default value.
• These annotations can be applied just before the
declaration of an element (constructor, method, • default value is optional.
classes, etc). • The return type of method should be either
primitive, enum, string, class name, or array of
primitive, enum, string, or class name type.
Syntax: Declaration
[Access Specifier] @interface<AnnotationName>
{
DataType <Method Name>() [default value];
}
Types of Annotation
• There are three types of annotations.
Marker Annotation
• An annotation that has no method
@interface MyAnnotation{}
Types of Annotation
Single-Value Annotation
• An annotation that has one method
@interface MyAnnotation{
int value();
}
• Can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
• To apply Single-Value Annotation
@MyAnnotation(value=10)
Types of Annotation
Multi-Value Annotation
• An annotation that has more than one method,
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
• Can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
• To apply Multi-Value Annotation
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
Built-in Annotations used in custom annotations
• @Target
• @Retention
• @Inherited
• @Documented
@Target
• Used to specify at which type, the annotation is used.
• The java.lang.annotation.ElementType enum declares many constants to specify the type of
element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:
Example
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
@Inherited
• By default, annotations are not inherited to subclasses.
• The @Inherited annotation marks the annotation to be inherited to
subclasses.
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also
class Superclass{}
class Subclass extends Superclass{}
@Documented
• The use of @Documented annotation in the code enables tools like
Javadoc to process it and include the annotation type information in
the generated document.
Custom annotation: creating, applying and accessing annotation
//Creating annotation //Accessing annotation
import java.lang.annotation.*; class TestCustomAnnotation1{
import java.lang.reflect.*; public static void main(String args[])throws
@Retention(RetentionPolicy.RUNTIME) Exception{
@Target(ElementType.METHOD) Hello h=new Hello();
@interface MyAnnotation{ Method m=h.getClass().getMethod("sayHello");
int value(); MyAnnotation
} manno=m.getAnnotation(MyAnnotation.class);
//Applying annotation System.out.println("value is: "+manno.value());
class Hello{ }}
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello
annotation");}
}
Spring Core Annotations
• @Component
• @ComponentScan
• @Configuration
• @Bean
• @Required
• @Autowired
• @Qualifier
• @Primary
• @Value
• @PropertySource
@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.
Example
@ComponentScan(basePackages = "com.sample")
@Configuration
public class ScanComponent
{
// ...
}
@Configuration
• It is a class-level annotation.
• The class annotated with @Configuration used by Spring Containers as a
source of bean definitions.
Example
@Configuration
public class Vehicle
{
@BeanVehicle engine()
{
return new Vehicle();
}
}
@Bean
• It is a method-level annotation.
• It is an alternative of XML <bean> tag.
• It tells the method to produce a bean to be managed by Spring Container.
Example
@Bean
public BeanExample beanExample()
{
return new BeanExample ();
}
@Required
• It applies to the bean setter method.
• It indicates that the annotated bean must be populated at configuration time with the required property
public class Machine
{
private Integer cost;
@Required
public void setCost(Integer cost)
{
this.cost = cost;
}
public Integer getCost()
{
return cost;
}
}
@Autowired
class Student {
@Autowired
Address address;
}
@Qualifier
• Eliminate the issue of which bean needs to be injected.
public class FooService {
@Autowired
@Qualifier("fooFormatter")
private Formatter formatter;
}
@Primary
• Give higher preference to a bean when there are multiple beans of the same type.
@Configuration
public class Config {
@Bean
public Employee JohnEmployee() {
return new Employee("John");
}
@Bean
@Primary
public Employee TonyEmployee() {
return new Employee("Tony");
}
}
@Value
Need a properties file to define the values we want to inject with the @Value
annotation.
And so, we'll first need to define a @PropertySource in our configuration class —
with the properties file name.
@PropertySource
class Student {
@Configuration
@Value("${student.rollNo}")
private int rollNo; @PropertySource("classpath:value.properties"
} )
public class StudentConfig {
property file “value.properties” //...
student.rollNo=1223 }
Spring Stereotype Annotations
• @Component annotation is the main Stereotype Annotation.
• There are some Stereotype meta-annotations which is derived from @Component
those are
• @Service
• @Repository
• @Controller
@Service: We specify a class with @Service to indicate that they’re holding the
business logic.
@Repository: We specify a class with @Repository to indicate that they’re dealing
with CRUD operations
@Controller: Responsible to handle user requests and return the appropriate
response. It is mostly used with REST Web Services
Spring Stereotype Annotations
@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.
Example
@Component
public class Student
{
.......
}
Spring Stereotype Annotations
@Controller
• The @Controller is a class-level annotation.
• 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.
Example
@Controller
@RequestMapping("books")
public class BooksController
{
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public Employee getBooksByName()
{ return booksTemplate; } }
Spring Stereotype Annotations
@Service
• It is also used at class level.
• It tells the Spring that class contains the business logic.
• Example
package com.sample;
@Service
public class TestService
{
public void service1()
{
//business code
}
}
Spring Stereotype Annotations
@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.
Example
package com.sample;
@Repository
public class TestRepository
{
public void delete()
{
//persistence code
}
}
@SpringBootApplication Annotation
• This annotation is used to mark the main class of a Spring Boot
application.
• It encapsulates @SpringBootConfiguration, @EnableAutoConfiguration,
and @ComponentScan annotations.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
@EnableAutoConfiguration: It auto-configures the bean that is present in the
classpath and configures it to run the methods
Spring Boot REST Annotations
@RestController
• Eliminates the need to annotate every request handling method of the controller class
with the @ResponseBody annotation.
• Allows to handle all REST APIs such as GET, POST, Delete, and PUT requests
• while @RestController simply return object and object data directly written into http
response as JSON orXML.
Spring Boot REST Annotations
@RequestMapping
• Map client requests with the appropriate method to serve the request
@RestController
class HelloControler
{
@RequestMapping("/")
public String hello()
{
return "Hello Spring Booot";
}
}
Spring Boot REST Annotations
HTTP method-specific shortcut
• Spring introduces annotation for different HTTP methods.
• The varients of @RequestMapping are ...
• @GetMapping
@RequestMapping(method = RequestMethod.GET)
• @PostMapping
@RequestMapping(method = RequestMethod.POST)
• @PutMapping
@RequestMapping(method = RequestMethod.PUT)
• @DeleteMapping
@RequestMapping(method =RequestMethod.DELETE)
Spring Boot REST Annotations
@PathVariable
• Bind value of variable at URL path with request handler’s method parameter
@ResponseBody
• Converts return type data into JSON format in case of non-string return type data
@RequestBody
• Sending input data in form of JSON/XML(Global data format) to a Spring Boot REST
producer application via request handler method
@RequestParam
• Binds the value of web request parameter with the value of Controller’s method
parameter.
• It acts just like getRequestParameter() method of HttpServletRequest.
• We send data to application using URL in the form of “URL?key=val“.
Spring Boot JPA Annotations
@Id
• @Id marks a field in a model class as the primary key
class Person {
@Id
Long id;
// ...
}
Spring Boot JPA Annotations
@Table
• Used for adding the table name in the particular MySQL database.
Syntax:
@Entity
@Table(name=”Student”)
public class Student {
…
}
Spring Boot JPA Annotations
@Column
• Used to specify the mapping between a basic entity attribute and the
database table column.
@Entity
• Used to specify that the currently annotate class represents an entity
type.
@GeneratedValue
• Specifies that the entity identifier value is automatically generated
using an identity column
Example
import java.util.*; import javax.persistence.*;
@Entity
@Table(name = "Student")
public class StudentInformation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int rollno; private String name;
public int getRollno() { return rollno; }
public StudentInformation(int rollno, String name)
{ this.rollno = rollno; this.name = name; }
public void setRollno(int rollno)
{ this.rollno = rollno; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }}