Springboot common annotation summary

1. Notes about the controller

@RestController:
Indicates that this class is a controller of a RESTful web service, converts the return value into JSON format and responds to the client

@RequestMapping:
Map the URL address and method of the request, used on a class or method, you can set the URL address, request method, request parameters, etc.

@RequestParam:
Get the value of the request parameter. Used on the parameters of the method, you can set the parameter name, whether it is required, the default value, etc.

@PathVariable:
Get the placeholder parameters in the URL and use them on the parameters of the method. You can set the parameter name, whether it is required, the default value, etc.

@RestController
@RequestMapping("/api")
public class UserController {
    
    
 
    @Autowired
    private UserService userService;
 
    @GetMapping("/users")
    public List<User> getUsers() {
    
    
        return userService.getAllUsers();
    }
 
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
    
    
        return userService.getUserById(id);
    }
 
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody User user) {
    
    
        userService.saveUser(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
 
    @PutMapping("/users/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
    
    
        User existingUser = userService.getUserById(id);
        if (existingUser != null) {
    
    
            userService.updateUser(user);
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
    
    
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
 
    @DeleteMapping("/users/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
    
    
        User existingUser = userService.getUserById(id);
        if (existingUser != null) {
    
    
            userService.deleteUser(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } else {
    
    
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}


The @RestController annotation is used in the code to indicate that this is a RESTful web service. The @RequestMapping annotation specifies the base URL path for handling HTTP requests. Dependency injection (@Autowired) is used to obtain UserService, which is used to process the business logic of the User entity. In the class, some methods for handling HTTP requests are defined: GET, POST, PUT, and DELETE.

Different annotations are used in the classes to specify their HTTP path and HTTP method, the @GetMapping annotation specifies the path used to handle HTTP GET requests, @PostMapping specifies the path used to handle HTTP POST requests, and some Spring MVC is also used Specific annotations, such as @PathVariable and @RequestBody, are used to obtain the value of a request parameter or request body. They also use the ResponseEntity class to encapsulate HTTP responses, and the HttpStatus enumeration to represent HTTP status codes.

2. Notes about automatic assembly

@Autowired:
Automatically assemble a Bean object, used on fields, methods, and constructors, you can set whether it is necessary, the name of the Bean, etc.

@Value:
Get the attribute value in the configuration file, use it on the field, method, constructor, you can set the attribute name, default value, etc.

@Component
public class AdminComponent {
    
    
 
    @Autowired
    private AdminService adminService;
 
    @Value("${system.config}")
    private String sysConfig;
 
    public void getCongfig() {
    
    
        System.out.println("system config is " + sysConfig);
    }
}

3. Component-related annotations
@Component:
Represents a component class that will be automatically scanned and loaded into the Spring context

@Service:
Represents a business service class that will be automatically scanned and loaded into the Spring context

@Repository:
Represents a data access class that will be automatically scanned and loaded into the Spring context

@Repository
public class UserRepositoryImpl implements UserRepository {
    
    
 
    @Autowired
    private SessionFactory sessionFactory;
 
    @Override
    public User findById(Long id) {
    
    
        Session session = sessionFactory.getCurrentSession();
        return session.get(User.class, id);
    }
 
    @Override
    public void save(User user) {
    
    
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }
 
    @Override
    public void delete(User user) {
    
    
        Session session = sessionFactory.getCurrentSession();
        session.delete(user);
    }
 
    @Override
    public List<User> findAll() {
    
    
        Session session = sessionFactory.getCurrentSession();
        CriteriaQuery<User> criteriaQuery = session.getCriteriaBuilder().createQuery(User.class);
        criteriaQuery.from(User.class);
        return session.createQuery(criteriaQuery).getResultList();
    }
}

4. Configuration-related annotations
@Configuration:
Represents a configuration class that will be automatically scanned and loaded into the Spring context. You can use the @Bean annotation to define a Bean object

@EnableAutoConfiguration:
Used to enable automatic configuration, which will automatically configure various Bean objects in the Spring context

@EnableAutoConfiguration
public class MyApplication {
    
    
    //...
}

@Conditional:
Used to conditionally load the Bean object, you can decide whether to load it according to certain conditions

@Configuration
public class SysConfig {
    
    
    @Bean
    @Conditional(SysCondition.class)
    public SysBean sysBean() {
    
    
        return new SysBean();
    }
}

public class SysCondition implements Condition {
    
    
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    
    
        return true; //返回 true 表示需要加载 SysBean 对象
    }
}

5. Combined annotation
@SpringBootApplication: including @Configuration, @EnableAutoConfiguration and @ComponentScan.

@Configuration: Indicates that the class is a configuration class, and you can use the @Bean annotation to define a Bean object

@EnableAutoConfiguration: Used to enable automatic configuration, which will automatically configure various Bean objects in the Spring context

@ComponentScan: Used to automatically scan and load qualified component classes. If the scan path is not set, the package and its subpackages of the class where the annotation is located will be scanned by default

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

Guess you like

Origin blog.csdn.net/weixin_43749805/article/details/130623201
Recommended