spring boot annotation use case

8 minutes reading time To
learn the springboot framework is to learn how to use its annotations.

Spring boot annotations and use cases

  1. @Bean

    "@Bean" is a method-level annotation similar to an XML tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory .

@Bean
public ExampleBean exampleBean() {
    
    
  return new ExampleBean();
}
  1. @Springbootapplication

    The "@SpringBootApplication" annotation triggers auto-configuration and component scanning. It combines three annotations: @Configuration, @ComponentScan and @EnabeAutoConfiguration.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

    "@Configuration" is a class-based annotation that indicates the definition of one or more bean methods in the class. Once the Sprint container encounters this annotation, it can process these spring beans to generate bean definitions and service requests at runtime.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigClass {
    
    
    @Bean
    public MyBean mybean() {
    
    
        return new MyBean();
    }
}
  1. @ComponentScan

    You can use the "@ComponentScan" annotation in conjunction with the "@Configuration" annotation to define components that require programmatic scanning. There are several parameters in this annotation. If no arguments are specified, the framework will scan the current package with subpackages. You can use the "base package" parameter to define specific packages to scan.

package TestPackage;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "TestPackage")

public class TestClass {
    
    

}
  1. @EnableAutoconfiguration

    This annotation allows you to automatically configure the program according to your requirements. The framework determines this auto-configuration based on the program and jars contained in the classpath. For example, if you add a "tomcat-embedded.jar" file, it will automatically configure the TomcatServlet Web server factory if there is no explicit declaration for its associated factory bean. Use the 'exclude' and 'exclude classname' parameters.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class TestClass {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(TestClass.class, args);
    }
}
  1. @RequestMapping

    The "@RequestMapping" annotation is used to map HTTP requests to REST and MVC controller methods in spring boot applications. It can be applied at class level or method level in controllers. Additionally, you can declare multiple request mappings using a list of values ​​in annotations.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ControllerClass {
    
    

    @ResponseBody
    @RequestMapping("/cart")
    public String getCart() {
    
    
        return "this is the cart!";
    }

    @ResponseBody
    @RequestMapping("/catalogue")
    public String getCatalogue() {
    
    
        return "this is the catalogue";
    }
}
  1. @GetMapping

    "@GetMapping" is a shortcut for the "@RequestMapping(method = RequestMethod.GET)" annotation to handle HTTP GET requests corresponding to the specified URL. The following class is annotated with "@RestController" to indicate that it can handle web requests. "@GetMapping" maps /hello to the hello() method

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    

  @GetMapping("/hello")
  public String hello() {
    
    
    return "Hello Spring Boot!";
  }
}
  1. @PostMapping

    "@PostMapping" is a shortcut for the "@RequestMapping(method = RequestMethod.POST)" annotation to handle HTTP GET requests corresponding to the specified URL. The following class is annotated with "@RestController" to indicate that it can handle web requests. "@PostMapping" maps /hello to the hello() method

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    

  @PostMapping("/hello")
  public String hello() {
    
    
    return "Hello Spring Boot!";
  }
}
  1. @RequestParam

    The "@RequestParam" annotation allows extraction of input query parameters, form data, etc. For example, suppose you have an endpoint /API/book that takes a query string parameter called id. You can then specify that parameter using the @RequestParam annotation in the following way.

@GetMapping("/api/book")
@ResponseBody
public String getBook(@RequestParam String id) {
    
    
    return "Book ID: " + id;
}
  1. @PathVariable

    The "@PathVariable" annotation allows to extract query parameters etc. from the request address. For example, suppose you have an endpoint /API/book/1234 that takes a dynamic address string parameter named id. You can then use the @PathVariable annotation to get that parameter.

@GetMapping("/api/book/{id}")
public String getBookForId(@PathVariable Integer id) {
    
    
    return "Book ID: " + id;
}
  1. @Service

    @Service is a class-level annotation to indicate that the class is a service class that defines business logic. For example, the @Service annotation below indicates that BankService is a service class that provides banking services.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BankService {
    
    

    private final BankInfo bankInfo;

    @Autowired
    public BankService(BankInfo bankInfo) {
    
    
        this.bankInfo = bankInfo;
    }
}
  1. @Component

    This annotation allows the framework to auto-detect component classes without writing any explicit code. The Spring framework scans for classes with @component, initializes them, and injects the required dependencies.

import org.springframework.stereotype.Component;

@Component
public class TestComponentAnnotation {
    
    

  public int multiply(int x, int y) {
    
    
    return x * y;
  }
}
  1. @Repository

    "@Repository" is a specialized version of the "@Component" annotation. It indicates that the class is a repository that contains data storage and other operations such as updating, deleting, searching and retrieving data on objects.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.demo.model.BookEntity;

@Repository
public interface BookRepository extends JpaRepository<BookEntity, Long>
{
    
    
}
  1. @Controller

    This class-based annotation is also a specialization of the "@Component" annotation, marking a class as a controller. It is typically used in conjunction with handler methods annotated with @RequestMapping and with Spring MVC applications. Spring scans these classes with this annotation and catches the @RequestMapping annotation. Below is an example of its usage.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    
    

    @RequestMapping("/hello")
    public String hello()
    {
    
    
        return "Hello Spring!";
    }
}
  1. @Autowired

    The "@Autowired" annotation can autowire beans on constructors, setter methods, properties, or methods with multiple parameters. The <property> tag in the XML configuration file can be eliminated when using the @Autowired annotation on the setter method.

import org.springframework.beans.factory.annotation.Autowired;

public class Product {
    
    
   private Product product;

   @Autowired
   public void setProduct( Product product ){
    
    
      this.product = product;
   }
   public Product getProduct( ) {
    
    
      return product;
   }
}
  1. @SpringBootTest

    As the name suggests, the @SpringBootTest annotation can be used on test classes that execute Spring Boot-based tests. When it loads the full application context, you can easily use it for integration tests .

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class DemoTest
{
    
    
  @Autowired
  private DemoController demoController;

  @Test
  public void contextLoads() throws Exception {
    
    
    assertThat(demoController).isNotNull();
  }
}
  1. @MockBean

    Using this annotation, mocks can be specified in the application context, and service or REST API endpoints can be mocked from within the program. When you run your application, Spring loads a mock version of the application context. You can specify this annotation at class and field level, and you can specify them in configuration classes. Below is an example using the "@MockBean" annotation.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductServiceTest {
    
    

  @Autowired
  private ProductService productService;

  @MockBean(name="Product")
  private Product product;

  @Test
  public void test(){
    
    
    when(product.findAll()).thenReturn(Collections.emptyList());
    assertTrue(productService.findAll().isEmpty());
  }
}

------ If the article is useful to you, thank you in the upper right corner >>> Like | Favorite<<<

Guess you like

Origin blog.csdn.net/win7583362/article/details/127409339