☀️
Dev7Days
  • 😄Welcome
  • Local Setup
    • ⚙️Setup Terminal
    • ⚙️Setup IDE
    • ⚙️Setup Neovim
  • Rust
    • 🦀Cargo
  • Java
    • 🍃Spring Boot
      • Spring Boot Annotaion
      • Spring Boot Learning
    • 🍃JDK vs JRE vs JVM
    • 🍃What is JDBC ?
    • 🍃What is Data Source in Java ?
    • 🍃Check vs Unchecked Exception
    • 🍃What is Servlet in Java ?
    • 🍃Filter vs Interceptor
    • 🍃Mockito
    • 🍃Maven CLI
    • 🍃Maven Archetype
  • Go
    • 🔹Go Routine and Channel
    • 🔹Go CLI
  • Ruby and Rails
    • ♦️Ruby Syntax
    • ♦️Rails Framework
    • ♦️Rails Structure
  • Fundamental
    • 📚Git Command
    • 📚Interpreter vs Compiler
    • 📚DTO vs DAO
    • 📚Http Status
    • 📚What is Batch Process ?
    • 📚Https
    • 📚Local Storage vs Session Storage vs Cookies
    • 📚Authentication & Authorization
    • 📚Database Index
    • 📚What is GRPC ?
    • 📚What is Microservice ?
  • Database
    • 🗃️What is Transaction ?
    • 🗃️ACID
  • Postgres
    • 🐘SELECT
    • 🐘Column Alias
    • 🐘Order By
    • 🐘SELECT DISTINCT
  • Elastic Search
    • 🔍What is Elastic Search ?
    • 🔍Node and Cluster
  • Kubernetes
    • ☸️What is Kubernetes ?
    • ☸️Kubernetes Architecture
      • Node
      • ETCD
      • Kube API Server
      • Controller Manager
      • Kube Scheduler
      • Kubelet
      • Kube Proxy
  • ☸️Pod
  • ☸️ReplicaSet
  • ☸️Deployment
  • ☸️Service
  • ☸️Config Map
  • ☸️Namespaces
  • ☸️Kube Apply Command
  • ☸️Scheduling
    • Manual Scheduling
    • Labels and Selectors
    • Taints and Tolerations
    • Node Selector
    • Node Affinity
    • Resource Requirements and Limits
    • DaemonSets
    • Static Pods
    • MultipleSchedulers
  • ☸️Monitoring
  • AWS
    • 🔸How can users access AWS ?
    • 🔸IAM
    • 🔸EC2
      • User Data
      • Instance Types
      • Security Group
      • Purchasing Options
      • Placement Groups
      • Elastic Network Interface (ENI)
      • EC2 Hibernate
      • EC2 Storage
    • 🔸ELB & ASG
      • Health Checks
      • Target Group
      • ELB Types
      • Sticky Sessions
      • Cross Zone Load Balancing
      • Load Balancer - SSL and SNI
      • Deregistration Delay
      • ASG
    • 🔸RDS & Aurora DB
      • RDS
        • Storage Auto Scaling
        • Read Replica
        • Multi AZ
        • RDS Custom
        • Backup
        • RDS Proxy
      • AWS Aurora
        • Read Replica
        • Endpoint and Auto Scaling
        • Aurora Serverless
        • Global Database
        • Machine Learning
        • Backup
        • Database Cloning
      • RDS & Aurora Restore options
      • RDS & Aurora Security
    • 🔸Elastic Cache
    • 🔸Route 53
      • Records
      • Hosted Zones
      • Health Check
      • Routing Policies
  • Backend Security
    • 🎩SQL Injection
    • 🎩Cross site script (XSS)
    • 🎩Cross site request forgery (CSRF)
    • 🎩Man in the Middle (MITM)
    • 🎩Insecure Direct Object Reference (IDOR)
    • 🎩Distributed denial of service (DDOS)
  • Medium
    • 👨‍💻Gamer to Coder
    • 🐳Docker
      • Docker #1
      • Docker #2
    • 💊DI and IOC
    • ☸️Kubernetes
  • Book
    • 📚System Design Interview - An Insider's Guide (Volume 1
Powered by GitBook
On this page
  • @Bean
  • @Configuration
  • @Component
  • @Primary
  • @ConfigurationProperties
  • @Builder
  • @RequiredArgsConstructor
  • @Data
  • @Accessor
  • @AllArgsConstructor
  • @NotNull
  • @NotEmpty
  • @NotBlank
  • @Valid
  • @Validated
  • @Transactional
  • @JsonIgnore
  • @JsonIgnoreProperties
  1. Java
  2. Spring Boot

Spring Boot Annotaion

Describe about usability for each annotaion in spring boot

@Bean

This annotaion will be declared on the method inside the class that has @Configuration for create a object or bean.

@Configuration

This annotaion will be declared on the class and when application start , spring will look for @Bean then generate bean (create object) for each method that has @Bean to spring container at runtime.

@Component

This annotaion will be declared on the class and object will be created from this class to spring container.

@Primary

When you have 2 objects with the same class but inside difference , This annotaion will determine which one is the main.

Example

// 2 method for create bean

 @Bean 
 public RestTemplate createRestTemplate(){
     return new RestTemplate(1000,"rest1"); 
 }
 
 @Bean 
 @Primary
 public RestTemplate createRestTemplate2(){
     return new RestTemplate(2000,"rest2"); 
 }
 
 //This service will create resttemplate2 
 public class Service {
     @Autowired 
     private RestTemplate rest2;
 }

@ConfigurationProperties

This annotaion will be declared on the class or method and use for load configuration from application.properties.

Example

// Create class
@ConfigurationProperties("spring.userConfig")    
@Component
public class UserConfig {
    private String username;
    private String password;
    
    public UserConfig(){
        return new UserConfig();
    }
}

//application.properties
spring.userConfig.username=name
spring.userConfig.password=pass
// Create class
public class UserConfig {
    private String username;
    private String password;
    
    @ConfigurationProperties("spring.userConfig")    
    public UserConfig(){
        this.username = user;
        this.password = pass
    }
}

//application.properties
spring.userConfig.username=name
spring.userConfig.password=pass

@Builder

This annotaion will be declared on the class for create a immutable object with builder pattern.

@RequiredArgsConstructor

This annotaion will be declared on the class for generate constructor. It will generate constructor for only attribute that has final or @NonNull.

Example

// Create class
@RequiredArgsConstructor
public class User{
    @NonNull
    private String username;
    @NonNull
    private String password;
    private String email;
    
    
    // This is constructor that will be generated 
    public User(String username,String password){
        this.username = username;
        this.password = password;
    }
}

@Data

This annotaion will be declared on the class that including @ToString , @EqualsAndHashCode , @Getter/@Setter and @RequiredArgsConstructor.

@Accessor

This annotation will be declared on the class for configure @Getter/@Setter.

Example

@Accessor(chain = true) it will determine setter method to return this instead void.

// Create class
@Data
@Accessor(chain = true)
public class User{
    private String username;
    private String pass;
}

//Can create object with this strategy
new User().setUsername("user").setPass("pass");  

@AllArgsConstructor

This annotaion will be declared on the class for generate constructor with all attributes.

Example

// Create class
@Data
@AllArgsConstructor
public class User{
    private String username;
    private String pass;
    private String email
    
    // This is constructor that will be generated 
    public User(String username,String password,String email){
        this.username = username;
        this.password = password;
        this.email = email;
    }
}

@NotNull

This annotation will be declared on attribute inside the class for mandatory value (not null value).

@NotEmpty

This annotation will be declared on attribute inside the class that the value mustn't be empty.

@NotBlank

This annotaion will be declared on attribute inside the class that the value mustn't be null and empty.

@Valid

This annotation will be declared with parameter for validation value. It validate by using JSR-303 or javax.validation on method and can use on attribute for nested object.

@Validated

This annotaion will be similar to @Valid but it supports for validation in group level and declares on the class.

@Transactional

This annotaion will be declared on the class or method for rollback SQL query. It will create proxy for method or class that add this annotaion (Proxy Pattern) , if unchecked exception occur it will rollback SQL query. For handle check exception you can use @Transactional(rollBackFor = "TestException.class" ) or (noRollBackFor = "TestException.class"). Furthermore the class implement interface class or the method that access modifier doesn't public can't use this annotation.

Example

// popular
@Transactional(noRollbackFor = { SQLException.class })
public void createCourseDeclarativeWithNoRollBack(Course course) throws SQLException {
    courseDao.create(course);
    throw new SQLException("Throwing exception for demoing rollback");
}
public void createCourseDefaultRatingProgramatic(Course course) {
    try {
       courseDao.create(course);
    } catch (Exception e) {
       TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}

@JsonIgnore

This annotaion will be declared on attribute inside object class to determine this class mustn't return this field in the response of endpoint.

Example

//Create class
@Data
public class User{
    private String username;
    @JsonIgnore
    private String pass;
    private String email;
}

// The response of endpoint that use User class
{
    "username": "user",
    "email": "test@mail.com"
}

@JsonIgnoreProperties

This annotation will be declared on the class for manage about ignore properties in JSON so it has much custom feature than @JsonIgnore.

Example

// Create class
@Data
@JsonIgnoreProperties({"pass","email"})
public class User{
    private String username;
    private String pass;
    private String email;
}

// The response of endpoint that use User class
{
    "username": "user"
}
/* 
UseCase
1. Create Service to call request API to another service(A to B).
2. Create response object of B in A service.
3. Create Controller that call 1. and this endpoint will return response 
that is the same as B response.
4. The problem will occur when service B send the response more field 
than A service response object.
*/

// Create class in A service
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User{
    private String username;
    private String pass;
    private String email;
}

//Create controller in A service (return User)
public User testController(){
}

/* The response from B service */
//expected
{
    "username": "user",
    "pass": "pass",
    "email": "test@mail.com"
}
//actual
{
    "username": "user",
    "pass": "pass",
    "email": "test@mail.com",
    "id": "123,
    "name": "bob"
}


/* The response from controller in A service */

//Before add annotaion
{
    "username": "user",
    "pass": "pass",
    "email": "test@mail.com",
    "id": "123,
    "name": "bob"
}

//After add annotaion

{
    "username": "user",
    "pass": "pass",
    "email": "test@mail.com"
}
PreviousSpring BootNextSpring Boot Learning

Last updated 2 years ago

🍃