Introduction of basic annotations of Spring Boot

 2021-07-15

Introduction of basic annotations of Spring Boot

You've probably seen annotations in the process of using the Spring Framework for programming, especially Spring Boot. It is often used to provide data information in Java source code. In this article, Hachinet will show how to use some of the most common annotations.

 

1. Knowledge of Spring Boot annotations


1.1 Dependency Injection (DI)

This is a design pattern, a set of code that reduces the dependencies between objects so that you can easily modify or extend your code later. Objects must depend on abstract classes, and their detailed instances are injected at program execution time.

1.2 Inversion of Control (IoC)

However, if you have a lot of dependencies (less than 10), you will need to inject them, which can be very time-consuming.

Imagine a class that needs to inject dozens of dependencies, which can be very time-consuming.

  • Instead of initializing the object in the usual way, just reverse the direction of control and send it to Spring.
  • Create a project and manage the memory of the object. "Reverse control control"
  • Spring Container is the place where all beans are stored.

 

2. Basic annotation


AI技術にかかせないアノテーションとは | 運営からのお知らせ | 沖縄イノベーションマッチングサイト | インダストリンク

2.1 @Autowire

Automatically embed the Bean generated by Spring Container in the class declared with @Autowire. When Spring "by Dependency Injection Mechanism" starts running, it runs a mechanism that uses annotations to scan the classes that create the bean. At the same time, it searches for those beans for the @Autowire declaration, finds the corresponding bean, and injects it into that bean.

Use @Autowire in the following three examples.

//Properties
@Service
public class UserService {

        @Autowired
        UserRepository userRepository;

        @Autowired
        FacebookUtil facebookUtil;
}
//Setter
@Service
public class User {
    
        Private String name;
        
        @Autowire
        void setName(String name) {
            this.name = name;
        }
}
//Contructor
@ServicepublicclassUser {
    
        private long id;

        private String name;

        @Autowire
        void user(long id, String name) {
            this.id = id;
            this.name = name;
        }
}

2.2 @Configuration

Used to indicate that a class declared using @Configuration declares one or more @Bean methods within that class.

Configuration beans in a project are typically placed in these configuration classes. For example, configure Elasticsearch, Thymeleaf, multilingual, and so on.

2.3 @Bean

When you highlight a method, it spawns a bean and tells Spring that it's managed by the Spring container.

All methods that use the @Bean annotation must be included in the Configuration class.

@Configuration

public class WebDriverConfig {

             @Bean

              public WebDriver Chrome() {

    System.setProperty("webdriver.chrome.driver",                                        

                               "/Downloads/chromedriver_linux64/chromedriver");  

                  return new ChromeDriver();

                       }

     }

2.4 @ComponentScan

Use this annotation to tell the Spring container: "You need to know which package in your project scans the annotations and creates the bean."

  @Configuration

  @ComponentScan(basePackages = "minhchuan.spring ")

        public class SpringComponentDemo {

                          // ...

          }

2.5 @Component

If the class uses this annotation, "Created as a bean and injected into all classes that need it."

  • If the class does not use @Component, the class cannot be @Autowired.
  • If you define a class for injection, you must use this annotation to mark the class so that Spring can recognize it.

2.6 @Service  

This is a special annotation for @Component for business, logic processing.

   

    @Service

      public class UserService {

   @Autowired  

           UserRepository userRepository

    @Autowired

             FacebookUtil facebookUtil;  

               }

     }

2.7 @Repository

This is also a special annotation for @Component. Used to manipulate the database.
Jpa provides basic selection, updates, etc., functionality. You can apply additional query creation.

Common interface: CrudRepository, JpaRepository, MongoRepositor, etc.

@Repository

   public interface UserRepository extends JpaRepository <User, Integer> {

    //Query Creation

    }

2.8 @Scope

This is the scope of beans that are created and destroyed under the control of Spring Container. If the bean was generated using the scope used and its customizations.

It will be the default scope when the singleton bean is generated. That is, "Beans are created only once and used by the container. There is only one bean in the container."

In other words, it means that the container loads only specific beans at a time.

  • Prototype: Use this scope because it requires a lot of beans, as opposed to a singleton.
  • Request: The bean is generated through the user's HTTP request. Used only in web applications.
  • Session: Beans are spawned via an HTTP session.

2.9 @ PropertySource and @Value

Use @PropertySource to tell Spring the location of the system configuration properties file.

Also, use @Value to get the value in the properties file.

 @Configuration

    @Property

        Source("classpath:application.properties")

         public class

             MongoDBConfiguration {

    @Value("${mongodb.url}") private String url;

       @Value("${mongodb.db}")

       private String name;

      }

2.10 @Valid

It is used to check if the data is correct.

 

  @Entity public class User {

      @Id

 @GeneratedValue private Long id;

  @NotEmpty

 

                  (message = "Please provide a name") private String name;

                 @NotEmpty(message = "Please provide a className")

                                      private String className; //... }

 

          @RestController public class UserController {

                @PostMapping("/users") Book newBook(

            Valid @RequestBody User user) {

     //...

            }}

In this case, if the property of the user object (name, className) is null, an error will occur.

2.11 @ReponseBody

The controller API tells the user to return a JsonObject object to the client instead of rendering the view page.

 

If you are considering offshore development, please feel free to contact us.

Here is our contact information.

Account Manager: Quan (Japanese/English available)

Phone number: (+84) 2462 900 388

Email: contact@hachinet.com

Please feel free to contact us for consultation/application by phone.

Click here for more information ▶