1. @ActiveProfiles
Used to declare active profiles - @ActiveProfiles("prod" (this prod is defined in the configuration class))
@RunWith()
@SpringBootTest
@ActiveProfiles("test")
public class MyApplicationTests {
@Test
public void contextLoads() {
// Your test code
}
}
The @ActiveProfiles("test") annotation tells the Spring Framework to activate the configuration file named test. This means that Spring will load all the beans and configurations associated with the test configuration file. If you have multiple profiles to activate, you can separate them with commas, e.g. @ActiveProfiles("test,test1").
2. @After
Advice, which flags code that will be run after each test method is executed, as opposed to @Before.
import ;
import ;
import ;
public class MyTest {
Before
public void setUp() {
// Run before each test method is executed
}
@Test
public void testMethod1() {
// Test method 1
}
@Test
public void testMethod2() {
// testMethod2
}
@After
public void tearDown() {
// Run after each test method execution
}
}
This annotation is mainly used to perform cleanup tasks, such as releasing resources, restoring the pre-test state, etc., to ensure test independence and repeatability.
3. @Before
Advice, which is executed before the original method.
4. @Around
Wrap-around advice (advice), Spring AOP (cutter-oriented programming) in an important annotation , wrap-around notification is a target method before and after the execution of the insertion of additional logic to enhance the processing , it can be in the method before the execution of the operation , and after the execution of the method operation , and even be able to control the execution of the target method with or without the modification of the return value or to throw an exception .
@Aspect
public class LoggingAspect {
@Around("execution(* .*.*(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = ();
// Logic executed before the execution of the target method
("Method " + ().getName() + " starts");
// Implementation of the target methodology
Object proceed = ();
// Logic executed after the execution of the target method
long endTime = ();
("Method " + ().getName() + " ends. Execution time: " + (endTime - startTime) + " ms");
return proceed;
}
}
caveat
- The proceed() method in a wrap-around notification must be called or the target method will not be executed.
- Wrap-around notifications need to be used with caution, as improper use can lead to errors in program logic or performance problems.
- Ensure that the return type of the wrap-around notification method matches the return type of the target method so that the result can be returned correctly.
- When handling exceptions in wrap-around notifications, it is important to pay attention to exception delivery and handling to avoid abnormal program termination.
5. @Aspect
One of the core annotations in Spring AOP (Aspect Oriented Programming) for declaring a class as a facade (Aspect)
The main role of @Aspect:
-
declarative cut: By
@Aspect
annotations, the Spring container is able to recognize which classes are cutover classes and thus treat them in a special way. - Defining Notifications: In a cutover class, you can define various Advices, such as Before Advice, After Advice, Around Advice, etc., to specify the logic that needs to be executed at different stages of the execution of the target method.
- Specify the entry point: With a Pointcut Expression, you can specify which methods of which classes need to be enhanced (i.e., which methods need to perform the logic defined in the notification).
Basic steps for using @Aspect:
-
Introducing dependencies: Ensure that you have introduced Spring AOP and AspectJ dependencies into your project.
-
Defining a Cutting Class: Use
@Aspect
annotation to declare a class as a faceted class. -
Defining Notifications: In a faceted class, use annotations provided by Spring AOP (such as the
@Before
、@After
、@Around
etc.) to define notifications. -
Specify the entry point: In the notification annotation, the notification is passed through the
value
maybepointcut
attribute to specify the entry point expression to specify which methods need to be augmented. -
Configuration cutout: Registers the facet class with the Spring container so that Spring can recognize and process it. This is usually done through Java configuration or XML configuration.
@Aspect
@Component // Alternatively, use @Configuration and @EnableAspectJAutoProxy.
public class LoggingAspect {
// Define an entry point expression
@Pointcut("execution(* . *. *(...))")
public void serviceLayerExecution() {}
// Define the before notification using an entry point expression and the @Before annotation.
@Before("serviceLayerExecution()")
public void logBeforeServiceMethod(JoinPoint joinPoint) {
("Before executing " + ().getName());
}
// Define the preceding notification using an entry point expression and the @Around annotation.
// @Around("serviceLayerExecution()")
// public void logBeforeServiceMethod(JoinPoint joinPoint) {
// ("Around executing " + ().getName());
// }
// Similarly, you can define other types of notifications such as @After, @AfterReturning, @AfterThrowing
caveat
- Ensure that your Spring container has enabled AOP support, which is typically implemented on the configuration class via the @EnableAspectJAutoProxy annotation.
- Entry point expressions are one of the powerful features of Spring AOP that allow you to specify exactly which methods need to be enhanced.
- Notification methods defined in a faceted class should not have return values (except for wrap-around notifications), and their parameter lists should match the parameter types required by Spring AOP.
- Specific use according to the business logic of their own code
6. @Autowired
The @Autowired annotation is a core annotation in the Spring framework for implementing dependency injection. It enables the Spring container to automatically recognize and inject beans required by fields, constructor parameters, or method parameters that are annotated with @Autowired. this greatly simplifies dependency management, allowing developers to focus more on the implementation of the business logic and less on how to configure and inject dependencies!
Working Principle
When the Spring container starts, it scans for classes marked by annotations such as @Component, @Service, @Repository, or @Controller and registers instances of those classes as beans in the Spring container. Then, for each field, constructor, or method marked @Autowired, the Spring container tries to find a bean of matching type in the container and injects it into the annotated location.
Usage Scenarios
- field injection: Use the @Autowired annotation directly on a field of the class, and the Spring container will automatically inject the matching bean into the field.
@Autowired
private UserRepository userRepository;
- constructor injection: By using the @Autowired annotation on the constructor of a class, the Spring container automatically injects the bean required by the constructor parameter when creating an instance of the class.
@Autowired
public UserService(UserRepository userRepository) {
= userRepository;
}
- Setter Injection: By using the @Autowired annotation on the setter method of a class, the Spring container automatically injects the required bean when the method is called.
@Autowired
public void setUserRepository(UserRepository userRepository) {
= userRepository;
}
Demo
vantage
- Reduced code coupling: Through dependency injection, the coupling between classes is reduced and easier to maintain and test.
- Easy to Configure: Using @Autowired simplifies the configuration process and reduces the complexity of XML configuration or Java configuration.
- Supports automatic assembly: The Spring container automatically recognizes and injects dependencies, improving development efficiency.
caveat
- Optional dependencies: If a dependency is optional, you can add the required = false attribute to the @Autowired annotation so that Spring will not throw an exception even if there is no matching bean.
- Multiple candidates: If there are multiple type-matched beans in the Spring container and you need to inject one of them, you may need to use the @Qualifier annotation to specify which bean to inject.
- circular dependency: @Autowired supports constructor-injected circular dependencies by default, but may require additional configuration or avoidance in the case of circular dependencies injected via fields.
7. @Bean
A core annotation in the Spring Framework that is used to declare methods in configuration classes and register the return values of those methods as beans in the Spring container.
corresponds English -ity, -ism, -ization
- Declare Bean: The @Bean annotation is used to tell the Spring container that the annotated method will return an object that is to be registered as a bean in the Spring application context.
- Managing Beans: Once an object is registered as a bean, the Spring container is responsible for managing its life cycle, including creation, assembly, and destruction.
utilization
- configuration class: The @Bean annotation is usually used in classes with the @Configuration annotation, which are called configuration classes.
- method level: @Bean is a method-level annotation to mark methods that return an object as a bean.
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
characterization
- dependency injection: The @Bean method can have dependencies on other beans, which will be automatically injected via method parameters.
- life cycle retracement: The @PostConstruct and @PreDestroy annotations can be used to define callback methods after bean initialization and before destruction.
- Specifying names and aliases: You can use the name or value attribute of the @Bean annotation to specify the name and alias of a bean.
- Specifying a Scope: You can use the @Scope annotation to specify the scope of a bean, e.g., singleton, prototype, and so on.
caveat
- method invocation: Although @Bean methods can be called, it is generally not recommended that they be called directly to obtain a bean instance, but rather through the Spring container.
- uniqueness: In the same configuration class, the name of the bean defined by the @Bean method is the method name by default. If there are multiple methods that return objects of the same type but with different names, they are registered as different beans.
- overloaded method: Although Java supports method overloading, be careful when using the @Bean annotation, as the Spring container may not handle overloaded @Bean methods correctly, leading to unpredictable behavior.
- @Autowired: Used to auto-assemble beans, and used in conjunction with @Bean to enable automatic injection of dependencies.
- @Component、@Repository、@Service、@Controller: These annotations are also used to define beans, but they are usually used to annotate specific classes, whereas @Bean is used to annotate methods in configured classes.
- **@Bean **: is an important tool for defining and managing beans in the Spring framework, through which developers can flexibly declare and manage beans in configuration classes, thus realizing the purpose of dependency injection and object management.
8. @Component
A core annotation in the Spring Framework that is primarily used to identify a class as a component in the Spring container as a Spring-managed bean.These classes are considered candidates for auto-detection when using annotation-based configuration and class path scanning. Also @Component is a meta annotation.
corresponds English -ity, -ism, -ization
- Component Identification: The @Component annotation is used to tell the Spring container that the annotated class is a component and should be managed by Spring.
- Auto Scan: When using annotation-based configuration, the Spring container scans for classes with the @Component annotation and automatically instantiates them as beans in the Spring application context.
utilization
- universal assembly: When a class is badly categorized to a specific annotation (e.g. @Controller, @Service, @Repository), it can be annotated with @Component.
- Simplified configuration: The @Component annotation simplifies the configuration of Spring applications, allowing developers to focus more on implementing business logic.
derivative note
- @Component has three common derived annotations: @Controller, @Service, and @Repository.
-
@Controller
: Used to identify the controller class, which handles Web requests. -
@Service
: Used to identify service layer classes that provide business logic. -
@Repository
: Used to identify Data Access Objects (DAOs) that provide data access functionality.
These derived annotations not only simplify component identification, but also bring additional benefits such as exception transformations (@Repository) or MVC control functions (@Controller)
-
dependency injection
- Classes annotated with @Component can be autowired in the same way as other classes. For example, you can use the @Autowired annotation in another component to automatically inject a component annotated with @Component.
- The @Component also supports specifying the name of the component, and the @Qualifier annotation allows components to be assembled by name.
caveat
- Although the @Component annotation is very flexible, in practice, it is recommended to choose the appropriate derived annotations (e.g., @Controller, @Service, @Repository) according to the purpose of the component in order to better organize and manage the code.
- When using the @Component annotation, it is important to make sure that the Spring container can scan for the annotated class. This is usually done by setting the --@ComponentScan annotation or the corresponding XML configuration.
9. @ComponentScan
Used to specify which packages the Spring container should scan to find and register classes with specific annotations (e.g. @Component, @Service, @Repository, @Controller, etc.) as Spring Beans
corresponds English -ity, -ism, -ization
Based on the defined scan path, classes that match the scan rules are assembled into the Spring container. In this way, the Spring container is able to manage the lifecycle of these classes and provide functionality such as dependency injection.
basic property
The @ComponentScan annotation contains several attributes to customize the behavior of component scanning:
- basePackages: Specifies the names of packages to be scanned, either as an array of strings or using dot-separated package paths.
- basePackageClasses: For certain classes in a given package, Spring scans the package and its subpackages for those classes.
- value: Same function as basePackages to specify the names of packages to be scanned.
- useDefaultFilters: Whether to use the default filter. If set to true, all classes with @Component, @Service, @Repository and @Controller annotations are scanned. If set to false, the default filters are not used and the filtering rules can be customized using the includeFilters and excludeFilters properties.
- includeFilters: Specifies which types of classes Spring should include. Multiple filters can be included, each containing a type and a class.
- excludeFilters: Specifies which types of classes Spring should not include. Usage is similar to includeFilters.
Demo
For example the package structure is as follows:
com
└── example
└── myapp
├──
└── service
├──
└──
In and , we annotate these two classes with the @Service annotation, respectively. Then, in the configuration class, we can use the @ComponentScan annotation to specify which packages Spring should scan:
@Configuration
@ComponentScan(basePackages = "")
public class AppConfig {
// Additional configuration beans and settings can be defined here.
}
In this example, the @ComponentScan annotation is used on the AppConfig class to specify that Spring should scan the package and its subpackages to register the component as a Spring bean.
Customized filters
If more granular control is needed, filtering rules can be customized through the includeFilters and excludeFilters properties. For example, only scanning for classes with specific annotations, etc.
@ComponentScan(
basePackages = "",
useDefaultFilters = false,
includeFilters = {
@Filter(type = , classes = {})
}
)
10. @Configuration
It is used to indicate that a class declares one or more @Bean methods and that these @Bean methods will be managed by the Spring container for generating and managing objects (i.e., beans) in the Spring application context. When you annotate a class with @Configuration, the class becomes a configuration class, and the Spring container processes the class at startup and recognizes the @Bean methods.
Main features
- configuration class: A class annotated with @Configuration is considered a configuration class, which allows you to define and initialize beans through the methods of the @Bean annotation.
- Total control: The configuration class gives you complete control over the creation and configuration of beans in the context of your Spring application.
- JavaConfig: @Configuration is part of JavaConfig, which refers to the way Spring applications are configured using Java classes and annotations instead of traditional XML files.
- Environmental abstraction: Configuration classes can also be used in conjunction with annotations such as @Profile, @PropertySource, etc. to support more complex configuration requirements such as environment-specific configuration and property file loading.
Demo
import ;
import ;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
AppConfig is a configuration class that defines a @Bean method called myService. When the Spring container starts, it calls the myService method to create an implementation of the MyService interface (MyServiceImpl) and register it as a bean in the Spring application context so that you can inject this MyService bean into other Spring-managed components through autowiring (e.g. @Autowired). in other Spring-managed components through autowiring (e.g. @Autowired).
caveat
- When you use methods annotated with @Bean in a configuration class, the Spring container ensures that there is only one instance of each bean (unless you use a specific scope annotation, such as @Scope, on the @Bean method).
- The configuration class itself is also managed by the Spring container, but it is not defined through the @Bean method. Instead, it is recognized by the classes with the @Configuration annotation that the Spring container scans for at startup.
- The @Bean methods in configuration classes can be called on each other to build dependencies between beans. However, be careful to avoid circular dependencies, which can cause the Spring container to throw an exception at startup.
11. @ConfigurationProperties
It is mainly used to bind properties from configuration files (such as or ) to Java objects. This annotation greatly simplifies the reading and management of configuration properties, enabling developers to decouple external configurations from the application code, improving code maintainability and extensibility.
Main features
- property binding: Binds properties from a configuration file to fields in a Java object, eliminating the need to manually write lots of getter and setter methods to read the configuration.
- type conversion: Supports automatic conversion of strings in configuration files to the corresponding types of Java objects (e.g. int, boolean, List, Map, etc.).
- default value: When the value of a property is not specified in the configuration file, the default value of a Java field can be used or specified via the @Value annotation.
- validate (a theory): Supports validity verification of configuration attributes to ensure that the configuration is correct.
- loose binding: Supports loose binding rules, i.e. the names of properties do not need to match strictly, e.g. my-property-name can be bound to the myPropertyName field.
Demo
-
- Adding Annotations: Add the @ConfigurationProperties annotation to the Java class and specify the prefix of the configuration file to bind to.
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private int version;
// getter cap (a poem) setter methodologies
}
-
- configuration file: Add the appropriate attributes to the or configuration file.
=My App Name
=1.0.0
myapp:
name: My App Name
version: 1.0.0
-
- Using Configurations: Get an instance of the MyAppProperties class through the Spring container and use the property values in it.
@Autowired
private MyAppProperties myAppProperties;
public void doSomething() {
String name = ();
int version = ();
// Other operations using attribute values
}
caveat
- prefix (linguistics): The prefix attribute of the @ConfigurationProperties annotation must be lowercase or an error will be reported.
- JavaBean Interface: Classes annotated with @ConfigurationProperties need to follow the JavaBean specification, i.e. provide public getter and setter methods.
- container component: Only components managed by the Spring container (e.g., classes annotated with @Component, @Service, etc.) can use the @ConfigurationProperties annotation.
- Configuration File Processor: You can import Spring Boot's profile processor dependencies to get code hints when writing configurations.
12. @ContextConfiguration
Often used in Spring testing scenarios, it is primarily used to load and configure the Spring context (ApplicationContext). This annotation allows developers to specify the location of a configuration file or configuration class to be loaded so that the Spring context can be properly built and initialized at runtime or test time.
corresponds English -ity, -ism, -ization
- Load Configuration File: Used to specify the location of Spring configuration files that contain configuration information for the Spring application, such as bean definitions, data source configurations, and so on.
- Loading Configuration Classes: Can also be used to specify the location of one or more Java configuration classes that contain the @Configuration annotation.
utilization
The @ContextConfiguration annotation can be used in two main ways:
-
- Specifies the configuration file:
Use the locations attribute to specify the location of an XML configuration file. One or more configuration files can be specified, with multiple files separated by commas or array syntax.
Example: @ContextConfiguration(locations = { "classpath:", "classpath:" })
- Specifies the configuration file:
-
- Specifies the configuration class:
Use the classes attribute to specify the location of one or more configuration classes. These classes must contain the @Configuration annotation.
Example: @ContextConfiguration(classes = { , })
- Specifies the configuration class:
principle
- When the @ContextConfiguration annotation is used, the Spring container creates and initializes an application context based on the specified configuration file or configuration class.
- If XML configuration files are specified, the Spring container loads these XML files through the appropriate ContextLoader (e.g., GenericXmlContextLoader).
- If configuration classes are specified, the Spring container uses the @Bean methods defined in those configuration classes to create and register the bean.
13. @Controller
Used to declare a class as a Spring MVC controller. When a class is tagged with the @Controller annotation, the Spring container detects the class and registers it as a Spring MVC controller that can handle methods mapped by HTTP requests.
corresponds English -ity, -ism, -ization
- Defining Controllers: The @Controller annotation marks a class as a Spring MVC controller, which means that the methods in the class can handle HTTP requests from the client.
- request mapping: While the @Controller annotation itself does not directly handle request mapping, it is often used in conjunction with @RequestMapping or its derived annotations (e.g., @GetMapping, @PostMapping, etc.) to map HTTP requests to specific methods in the controller.
- view resolution: The controller methods usually return a view name or ModelAndView object, and Spring MVC finds the appropriate view template based on this return value and renders it as an HTML response back to the client.
- data binding: Controller methods can receive request parameters, path variables, etc. and automatically bind them to method parameters, which simplifies the process of data extraction and processing.
Demo
- Add @Controller annotation: Mark the class as a controller by adding the @Controller annotation before the class definition.
@Controller
public class MyController {
}
- Defining request handling methods: Define methods in the controller class and use @RequestMapping or its derived annotations to map HTTP requests.
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
("message", "Hello, Spring MVC!"); return "hello"; // Return the view name.
return "hello"; // Returns the view name, and Spring MVC will find the appropriate view template to render it
}
}
- Configuring the View Parser: In the Spring MVC configuration, you need to configure a ViewResolver so that Spring MVC can find the corresponding view template based on the view name returned by the controller method.
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
("/WEB-INF/views/");
(".jsp");
return resolver;
}
caveat
- Not to be confused with @RestController: @RestController is a combination of @Controller and @ResponseBody annotations that are used to create RESTful Web services. You should use @RestController if your controller methods primarily return data such as JSON or XML rather than views.
- path matching: The path defined in the @RequestMapping annotation is relative to the application context path.
- Method parameters and return values: Controller methods can take various types of parameters, such as @RequestParam, @PathVariable, Model, etc., and can return String (view name), ModelAndView, ResponseEntity, void (used with HttpServletResponse), etc. and so on.
- Exception handling: An exception handler method can be defined via the @ExceptionHandler annotation to handle exceptions thrown in the controller.
- interceptor: You can create interceptors by implementing the HandlerInterceptor interface and registering them in the Spring MVC configuration to execute customized code at different stages of the request processing flow.
14. @ExceptionHandler
An annotation in Spring MVC to handle exceptions thrown in the controller. When you handle requests in the controller, you may encounter various exceptions, such as data validation failure, resource not found, insufficient privileges, etc. You can define one or more methods to handle these exceptions specifically, thus avoiding the need to handle them directly in the controller methods. Using the @ExceptionHandler annotation, you can define one or more methods to specifically handle these exceptions, thus avoiding dealing with the exception logic directly in the controller methods and making the code clearer and easier to maintain.
utilization
- Defining Exception Handling Methods: In the controller, you can use the @ExceptionHandler annotation to mark one or more methods as exception handlers. These methods take a parameter of an exception type and can return a view name, ModelAndView object, ResponseEntity, or any other response type supported by Spring MVC.
- Specifying an Exception Type: The @ExceptionHandler annotation can specify one or more exception types, indicating which types of exceptions the method will handle. If no exception type is specified, the method will act as the default exception handler, handling all exceptions not caught by other @ExceptionHandler methods.
- return value: The return value of an exception handling method determines how to respond to the client. You can return a view name to render an error page, or a ResponseEntity object containing the error message.
Demo
@Controller
public class MyController {
// Handling specific types of exceptions
@ExceptionHandler(value = )
public ResponseEntity<String> handleMyCustomException(MyCustomException ex) {
// Handle the exception logic
return (HttpStatus.BAD_REQUEST).body("Custom Exception Handler");
}
// Handle all uncaught exceptions (optional)
@ExceptionHandler()
public String handleAllExceptions(Exception ex) {
// Logging, etc.
return "error"; // return the view name of the error page
}
// Controller methods
@GetMapping("/somePath")
public String someMethod() {
// Assuming a MyCustomException is thrown here
throw new MyCustomException("This is a custom exception"); }
}
// Custom Exception Classes
public static class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message); }
}
}
}
caveat
- Global Exception Handling: If you want to handle exceptions centrally throughout your application, rather than separately in each controller, you can create a class that implements the HandlerExceptionResolver interface or, more simply, define a global exception handling class using the @ControllerAdvice annotation.
- Exception Priority: If there are multiple @ExceptionHandler methods that can handle the same exception, Spring MVC selects the first matching method based on the order in which the methods are defined (from top to bottom). Therefore, you should pay attention to the order in which the exception handling methods are defined to ensure that they are called in the order you expect them to be called.
- Logging: In the exception handling methods, don't forget to record exception information to the log for debugging and tracing in case of problems.
- Responding to the client: Ensure that your exception handling methods return clear, useful error messages to the client to improve user experience and system maintainability.
15. @ModelAttribute
An annotation in the Spring Framework that is primarily used to bind data from an HTTP request to a model object and render it in a view. It can be applied to method parameters or to the method itself and has flexible data handling capabilities.
utilization
- Method Parameters:
When the @ModelAttribute annotation is used for a method parameter, it indicates that the corresponding attribute value is taken from the model and bound to the method parameter. This is typically used to handle form submissions or query parameters in URLs, automatically populating the data in the request into the corresponding JavaBean object and adding it to the model for easy use by subsequent methods or views.
@GetMapping("/users/{id}")
public String getUser(@PathVariable("id") int userId, @ModelAttribute("user") User user) {
// Assuming we're getting the User object from the database based on the userId here
user = (userId);
// When the method executes, the user parameter already contains the User object retrieved from the database.
// ...
return "userPage"; // The method is executed with the user parameter already containing the User object retrieved from the database // ...
}
The @ModelAttribute("user") annotation binds an attribute named "user" in the request or model to the parameter user of type User. Note, however, that the actual usage scenario here may be different, as we would not normally use @ModelAttribute on a parameter that has already been fetched by annotations such as @PathVariable. The main purpose of the example here is to illustrate the usage of @ModelAttribute on method parameters.
- Method level:
When the @ModelAttribute annotation is used on the method itself, it indicates that the method's return value should be added to the model. This is often used to prepare shared model data before multiple requests are processed by the method.
@ModelAttribute
public void addAttributes(Model model) {
("msg", "Hello, Spring MVC!");
}
@GetMapping("/")
public String home() {
// Here you can directly use the model's"msg"causality
// ...
return "homePage";
}
The addAttributes method uses the @ModelAttribute annotation, and its return value (which is actually void, but adds data to the model via the method) is executed before each request processing method, adding an attribute named "msg" to the model. This adds an attribute called "msg" to the model so that this attribute can be used directly in subsequent request processing methods (such as the home method).
specificities
- auto-bind: Request parameters can be automatically bound to model objects, simplifying the process of data binding.
- Flexible Configuration: You can flexibly control the names of the attributes in the model by specifying the attribute names.
- prioritization: Methods annotated with @ModelAttribute are executed in preference to other request processing methods in the controller, ensuring that the model data is ready before the request is processed.
caveat
- The methods of the @ModelAttribute annotation are executed before every request processing method in the controller (unless a specific condition prevents them from executing), so care needs to be taken when using them to avoid unnecessary performance overhead.
- When the @ModelAttribute annotation is used for a method parameter, Spring tries to look up and bind data from the request if the corresponding attribute does not exist in the model; if the corresponding attribute already exists in the model, the attribute value from the model is used directly.
- When using the @ModelAttribute annotation, you can control the names of attributes in the model by specifying the attribute name; when not specified, the first lowercase letter of the return type is used as the attribute name by default (for method-level @ModelAttribute).
16. @Transactional
An annotation in the Spring Framework for declarative transaction management. It allows developers to declare that a method or class requires transaction support through a simple annotation without having to write complex transaction management code.Spring automatically creates proxy objects for these methods or classes at runtime and applies transaction management when the methods of these objects are executed.
utilization
- Business logic needs to ensure data consistency: When multiple database operations need to be performed as a whole, using @Transactional ensures that they all either succeed or are rolled back if an error is encountered, thus maintaining data consistency.
- Streamlining of service management: With declarative transaction management, developers can separate the logic of transaction management from the business code and focus on the implementation of the business logic without having to deal directly with tedious transactions such as opening, committing, or rolling back transactions.
- Improve code readability and maintainability: Using the @Transactional annotation makes the code more concise and easier to understand and maintain.
utilization
@Transactional can be applied on interface definitions, methods in interfaces, class definitions or methods in classes. Note, however, that due to limitations of the Spring proxy mechanism, this annotation may not work as well as expected on interface definitions or interface methods, so it is usually recommended to apply it to specific class methods.
@Service
public class MyService {
@Transactional
public void myMethod() {
// Perform database operations
}
}
The myMethod method is marked as transactional. When this method is called, Spring automatically creates a transaction context for the execution of the method and decides whether to commit or roll back the transaction at the end of the method's execution, depending on whether or not an exception occurs.
causality
The @Transactional annotation also provides several attributes that allow developers to have more granular control over the behavior of the transaction, for example:
- propagation: the propagation behavior of a transaction, defining how the current method interacts with an already existing transaction.
- isolation: the isolation level of a transaction, which defines the visibility of changes in the transaction to other transactions.
- timeout: the timeout of the transaction, if this time limit is exceeded, the transaction will be rolled back automatically.
- readOnly: Marks whether the transaction is read-only or not. Read-only transactions are used in scenarios where the data does not need to be modified, which can improve performance.
- rollbackFor and rollbackForClassName: defines which exceptions cause the transaction to be rolled back.
- noRollbackFor and noRollbackForClassName: defines which exceptions will not result in a transaction rollback.
caveat
- Method visibility: Methods annotated with @Transactional must be public because Spring AOP is implemented through the proxy mechanism, which requires that the proxied method must be public.
- Self-call issues: When one @Transactional annotated method calls another @Transactional annotated method in the same class, the propagation behavior of the transaction may not work as expected because the self-invocation does not pass through the proxy object, and thus transaction management is not triggered.
- Exception handling: By default, runtime exceptions and errors cause a transaction to be rolled back, while checked exceptions do not. However, it is possible to customize which exceptions cause a transaction to be rolled back by using the rollbackFor and noRollbackFor attributes of the @Transactional annotation.
17. @Value
An annotation in the Spring Framework that is used to inject values from a configuration file (such as a properties or YAML file) into fields of a Spring-managed bean. This annotation is typically used in conjunction with @ConfigurationProperties or directly in Spring components (e.g., @Component, @Service, @Controller, etc.) to read values from an external configuration source (e.g., or file).
utilization
- Injecting basic type values: e.g. strings, integers, booleans, etc.
- Injecting complex type values: such as using SpEL (Spring Expression Language) expressions to inject more complex values or perform some operations.
- Used with @ConfigurationProperties: While @ConfigurationProperties provides a more powerful way to bind a set of configurations to a Java object, @Value is still very useful for simple value injection.
Demo
=MyApp
=This is my application
=true
=123
import ;
import ;
@Component
public class MyAppProperties {
@Value("${}")
private String name;
@Value("${}")
private String description;
@Value("${}")
private boolean enabled;
@Value("${}")
private int number;
// getters and setters
}
caveat
- SpEL expression: The @Value annotation also supports SpEL expressions, which allow you to perform more complex operations such as string concatenation, conditional judgment, and so on.
- default value: You can provide a default value for the @Value annotation, e.g. @Value("${:defaultValue}"), if you don't find a corresponding property in the configuration file.
- type safety: While the @Value annotation provides a convenient way to inject values, it may not be as type-safe as @ConfigurationProperties, which allows you to validate the value of a configuration property through JavaBean validation.
- Environment Variables and Command Line Arguments: Spring Boot also allows you to override values in the or file with environment variables and command line arguments. These values can also be injected into your application using the @Value annotation.
18. @WebAppConfiguration
A class-level annotation in the Spring Framework, mainly used in Spring MVC integration tests to specify that the ApplicationContext loaded by the test class should be a WebApplicationContext.This annotation simulates a ServletContext during testing and builds a WebApplicationContext, thus providing a Web application environment for the test environment.
corresponds English -ity, -ism, -ization
- integration test: Mainly used in integration testing of Spring MVC applications to ensure that tests can be run in the context of the web application.
- simulated environment: Through the simulation of ServletContext , so that the test can be closer to the actual Web operating environment .
characterization
- Class-level annotations: It must be applied to the test class, not the test method.
- auto-configuration: In a Spring Boot application, when @WebAppConfiguration is applied to an @Configuration class, Spring Boot automatically configures a web environment, including starting a Servlet container (e.g., Tomcat) and handling HTTP requests.
- combine: Typically used with the @ContextConfiguration annotation to specify the configuration location or configuration class for the WebApplicationContext.
Demo
import ;
import .junit4.SpringJUnit4ClassRunner;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@RunWith()
@WebAppConfiguration
@ContextConfiguration("classpath:spring/")
public class MyWebControllerTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
= ().build();
}
@Test
public void testMyController() throws Exception {
// utilizationmockMvcto simulateHTTPRequest and validate the response
}
}
caveat
- Spring Version: In Spring 4.0 and later, while @WebAppConfiguration is still available, Spring provides a more flexible way to specify the ApplicationContext, so in some cases it may no longer be necessary to explicitly use @WebAppConfiguration.
- Resource Path: @WebAppConfiguration allows overriding the default web resource path via its value() attribute, thus providing more flexible configuration options.
- inherited: Since Spring Framework 5.3, the @WebAppConfiguration annotation can be automatically inherited from enclosing test classes, which simplifies the use and management of the annotation.
19. @Order
Used to define the priority of the execution order of the bean in the Spring IOC container (the order here can also be understood as the order of storage into the container). It does not directly control the order in which the beans are loaded, but rather affects the order in which the beans are executed in specific scenarios, such as dependency injection, event listening, interceptor/filter execution and so on.
utilization
-
Bean loading order:
In the configuration class, you can use the @Order annotation to specify the order in which beans are created in the Spring container. This is especially useful for beans that depend on the initialization order of other beans. Note that @Order does not strictly guarantee the order in which beans are loaded, especially in concurrent environments, but it does provide a prioritization guide for execution. -
Filter and interceptor order:
In web applications, the @Order annotation can be used to specify the order in which filters and interceptors are executed. By setting different @Order values, you can ensure that they are executed in the specified order. -
Event Listener Order:
In the Spring Framework, the @Order annotation can be used to specify the order of execution of event listeners. This helps to ensure that event listeners receive and process events in a specific order. -
AOP Cutting Order:
The @Order annotation can be used to specify the execution order of the facets when using Spring AOP for method interception. By setting different @Order values, you can control the execution order of the facets, thus enabling multi-level interception of methods. -
JUnit test execution order:
In JUnit tests, the @Order annotation can also be used to define the order in which test methods are executed. This helps to ensure that tests run in the expected order, especially if there are dependencies between tests.
Demo
@Component
@Order(1)
public class FirstBean {
// ...
}
@Component
@Order(2)
public class SecondBean {
// ...
}
The FirstBean will be created (or executed in priority, depending on the context) before the SecondBean.
caveat
-
ordinal value:
The @Order annotation receives an integer value as a parameter that indicates the order. The lower the value, the higher the priority, meaning that the component or operation will be executed or created earlier. -
default value:
If the @Order annotation does not specify a value, it will use Ordered.LOWEST_PRECEDENCE as the default value, which is usually Integer.MAX_VALUE, indicating the lowest priority. -
concurrent environment:
In a concurrent environment, the @Order annotation does not guarantee a strict order of execution. It is more of a guide to provide a prioritization of execution. -
Relationship to @Priority:
The @Priority annotation, which is part of JSR-250, is functionally similar to @Order, but has broader applications, including in CDI (Contexts and Dependency Injection).
20. @SpringBootTest
is a very important test annotation in Spring Boot , it simplifies the configuration and execution process of integration tests , making it easier for developers to create test environments close to the production environment .
corresponds English -ity, -ism, -ization
- Creating an Application Context: The main use of the @SpringBootTest annotation is to facilitate the creation of an application context (ApplicationContext) during testing. It tells Spring Boot to look for a main configuration class (e.g. a class with @SpringBootApplication) and use it to start the Spring application context.
- integration test: This annotation is typically used to test Spring components, especially those that need to interact with the Spring container. It simulates a complete Spring Boot application environment, including loading all Spring configurations and beans, thus enabling tests to run in a real application environment.
utilization
- Default behavior:
- By default, @SpringBootTest loads the configuration in the or file and starts a Spring application context.
- If your application has more than one configuration class, you can specify which configuration classes to load via the classes attribute.
- Flexible configuration:
- excludeAutoConfiguration: Use the excludeAutoConfiguration property to exclude specific autoconfigurations.
- properties: Use the properties attribute to specify the values of the properties to be used during testing to override the default configuration.
- webEnvironment: Specify the web environment through the webEnvironment attribute. Supported modes include MOCK (default, simulates a Servlet environment), RANDOM_PORT (starts the embedded web server and listens on a random port), DEFINED_PORT (starts the embedded web server and listens on the specified port), and so on.
- Used in conjunction with other annotations:
- @SpringBootTest can be used with other Spring annotations such as @DataJpaTest, @RestClientTest, etc. to provide a more specific test environment.
- If you need to use a mock bean in your tests, you can use the @MockBean annotation in conjunction.
- When testing Spring MVC controllers, you can use a combination of @SpringBootTest and @WebMvcTest.
- Automatic injection function:
- In the test class using the @SpringBootTest annotation, you can automatically inject the required components and configurations through Spring's @Autowired annotation to facilitate integration testing.
Demo
import ;
import ;
import ;
import static ;
@SpringBootTest
public class MyApplicationTests {
@Autowired
private MyService myService;
@Test
public void testService() {
// utilizationmyServicePerform some test operations...
assertNotNull(myService, "myService should not be null");
// Other test logic...
}
}
The @SpringBootTest annotation ensures that the application context of MyApplication is loaded, which allows MyService to be automatically injected into the test class. This allows us to use MyService in our tests as if it were managed by Spring for integration testing.
21. @PointCut
A core annotation in the AspectJ framework (a framework for facet-oriented programming), also widely used in Spring AOP (facet-oriented programming). It is used to define a point of entry (Pointcut), that is, to specify the connection point (Join Point) on which to apply a cut (Aspect) enhancement logic.
define
- Define the entry point expression: The @Pointcut annotation is followed by a string that is an entry point expression that specifies which methods will be intercepted or enhanced.
-
expression format: Usually an execution expression is used, of the form
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
. Where the individual parts are optional and can be wildcarded (e.g. *) to represent arbitrary values.
make up
- Modifier matching (modifier-pattern?): Method modifiers, such as public, protected, etc., are optional.
- Return value matching (ret-type-pattern): The return type of the method, which can be of any type indicated by *, or a specific type can be specified.
- Class path matching (declaring-type-pattern?): The path to the class where the method is located, you can specify a specific class name or package name, the package name can be followed by . It can be followed by ... to indicate all the classes under the package and its sub-packages.
- Method name matching (name-pattern): Specific method names can also be used withdenotes an arbitrary method name, orSomeMethod denotes a method name ending in SomeMethod.
- Parameter matching (param-pattern): A method's parameter list can be represented by * for any parameter, (String) for a parameter of type String, and (String, int) for two parameters, the first of type String and the second of type int. It is also possible to use (...) to denote any number and type of parameters.
- Exception type matching (throws-pattern?): The type of exception thrown by the method, optional.
usage
- Match all methods:@Pointcut("execution(* *(..))")
- Match all public methods under a specific package:@Pointcut("execution(public * ..(..))")
- Match all methods under a specific class and its subpackages:@Pointcut("execution(* ..*(..))")
- combinatorial expression: You can combine multiple entry point expressions using logical operators such as &&, ||, ! and other logical operators to combine multiple entry point expressions.
- Reusing entry point expressions: Define the entry point expression in a method and then refer to this entry point in other notifications (Advices) by method name, thus enabling code reuse.
Demo
@Aspect
@Component
@Slf4j
@Order(1)
public class SqlLoggingAspect {
//Define the tangent point
@Pointcut("execution(* ..*(..))")
public void repositoryExecution() {}
// Execute before the entry point
@Before("repositoryExecution()")
public void logBefore(JoinPoint joinPoint) {
("Executing method: " + ().getName());
Object[] args = ();
}
}
caveat
- Readability and maintainability: Extracting the entry point expression into a separate method improves the readability and maintainability of the code.
- Performance considerations: While reusing entry point expressions can improve code readability and maintainability, too many abstractions and combinations may degrade performance because entry point expressions need to be parsed and matched each time a notification is executed.
22. @Service
The @Service annotation is a Spring Framework annotation that is used to annotate components in the Service Layer, one of the core ideas of the Spring Framework is Dependency Injection (DI), and the @Service annotation is part of Spring's Dependency Injection functionality. The @Service annotation enables Spring to automatically detect annotated classes, instantiate, configure and manage them, and inject these instances into classes that need them (e.g., Controller Layer classes).
corresponds English -ity, -ism, -ization
- Service Tier Component Identification: The main purpose of the @Service annotation is to tell Spring that this is a service tier component. The service tier is usually responsible for the implementation of business logic, and sits between the presentation tier (e.g., the controller tier) and the persistence tier (e.g., the data access tier).
- automated assembly: The Spring container can scan for classes annotated with @Service and automatically register them as a bean in the Spring application context so that other components, such as controllers, can use these service layer components via dependency injection.
- transaction managementSpring allows you to use the @Transactional annotation on service tier methods to manage transactions declaratively, even though the @Service annotation does not directly provide transaction management functionality.
Demo
import ;
@Service
public class UserService {
// Here you can inject other dependencies, such as data access layer components.
public User getUserById(Long id) {
// Implement the business logic to get the user based on their ID.
// ...
return new User(); }
}
// Other business methods...
}
The UserService class is annotated with the @Service annotation to indicate that it is a service layer component, and the Spring container automatically detects this class and registers it as a bean, which can then be used via dependency injection wherever needed.
caveat
- Although the @Service annotation is provided by Spring, it is actually a generic annotation that can be used on any tier of components. However, according to Spring's best practices, we usually use @Service for service tier components, @Repository for data access tier components, @Controller for controller tier components, and so on.
- When using the @Service annotation, you need to make sure that your Spring configuration (either XML-based or Java-based) scans the package where the annotated class resides. This is usually done by adding the @ComponentScan annotation to the configuration class.
- If you are using Spring Boot, there is usually no need to explicitly configure package scanning, because Spring Boot automatically scans the package where the startup class resides and all components under its subpackages.
23. @SpingBootApplication
A core annotation in Spring Boot that is primarily used to mark up the main configuration class of a Spring Boot application. This annotation is a composite annotation that combines several other annotations from the Spring framework to simplify the process of configuring and launching Spring Boot applications.
make up
The @SpringBootApplication annotation is actually a collection of the following three annotations:
- @SpringBootConfiguration: This is a special form of @Configuration used to define a configuration class. It indicates that the class can use Spring Boot's autoconfiguration features and can be managed by the Spring container.
- @EnableAutoConfiguration: This annotation enables Spring Boot's auto-configuration mechanism, which automatically configures various Spring frameworks and third-party libraries based on the project's class paths and dependencies, reducing the effort of manual configuration.
-
@ComponentScan: This annotation is used to specify the base package path of the components to be scanned by the Spring container. By default, it will scan for components in the current package and its sub-packages, such as those created using the
@Component
、@Service
、@Repository
cap (a poem)@Controller
annotated classes and register them as beans in the Spring application context.
corresponds English -ity, -ism, -ization
- Simplified configuration: The @SpringBootApplication annotation enables developers to quickly get a Spring Boot application up and running without a lot of manual configuration.
- auto-configuration: Spring Boot provides out-of-the-box functionality by automatically configuring all aspects of the application, such as database connectivity, MVC configuration, etc., based on project dependencies and beans in the class path.
- Component Scanning: Classes with annotations such as @Component, @Service, @Repository and @Controller are automatically scanned and registered as Spring beans, making it easy for developers to use and manage these components.
- bootstrap logo: Identifies the class marked with the @SpringBootApplication annotation as the entry point for a Spring Boot application. When a Spring Boot application is run, the class marked with the @SpringBootApplication annotation is loaded and started first, thus starting the entire application.
Demo
The @SpringBootApplication annotation is added to the main class.
import ;
import ;
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
(, args);
}
// Additional methods or components can be defined here
}
The @SpringBootApplication annotation simplifies the process of starting a Spring Boot application. When the main method is run, Spring Boot automatically configures and starts the application.
Customized Configuration
@SpringBootApplication
Annotations also allow developers to customize the configuration through their properties. For example, using theexclude
attribute can exclude specific autoconfiguration classes to avoid unwanted autoconfiguration.
24. @Profile
Mainly used to define a specific configuration environment (profile), in order to load different configurations or beans in different environments
corresponds English -ity, -ism, -ization
- environmental distinction: During software development, it is often necessary to distinguish between different environments, such as the development environment (dev), the test environment (test), and the production environment (prod). Each environment may have different configuration requirements, such as database connectivity, logging levels, etc. The @Profile annotation allows developers to configure different environments for different purposes. The @Profile annotation allows developers to define different configurations for different environments, thus enabling flexible switching between environments.
- Conditionalized Bean Creation: With the @Profile annotation, you can specify that a bean or configuration class will only be created and loaded under certain circumstances. This helps to reduce unnecessary loading of resources and improve the speed and efficiency of application startup.
- Improved maintainability and scalability: By defining different configurations for different environments, the application can be made more modular and easy to maintain and extend. When you need to add new environments or modify the configuration of existing environments, you only need to modify the corresponding configuration class or bean, without modifying the entire application code.
utilization
- Modifying Classes: @Profile can directly modify a configuration class (i.e., a class with the @Configuration annotation) to indicate that the configuration class and its internal bean definitions are valid only in the specified environment.
@Configuration
@Profile("dev")
public class DevConfig {
// Define development environment-specific beans.
}
- Modifying Methods: In a configuration class, @Profile can also modify the @Bean method to indicate that the bean defined by the method will only be created in the specified environment.
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
// Returns the data source for the development environment.
}
@Bean
@Profile("prod")
public DataSource prodDataSource() {
// Returns the data source for the production environment
}
}
- Combined Use: @Profile also supports combining multiple environment names, separated by commas. This indicates that the configuration or bean will take effect in multiple environments.
@Bean
@Profile("dev,test")
public DataSource devTestDataSource() {
// Returns a data source common to both development and test environments.
}
Note: You have to activate the Profile when you use it.
In the or file, specify the currently active Profile by setting the property.
#
=dev
#
spring:
profiles:
active: dev
25. @Reponsitory
Components dedicated to the data access layer (DAO layer)
corresponds English -ity, -ism, -ization
- Identify the data access layer: The @Repository annotation identifies classes in the data access layer (DAO layer) that are typically responsible for interacting with the database and performing CRUD (create, read, update, delete) operations on data.
- Automatic detection and management: The @Repository annotation enables the Spring container to automatically detect and manage these DAO components, injecting them into the rest of the application as beans.
- Exception handling: The @Repository annotation also provides a data access related exception handling mechanism that automatically converts database related exceptions into Spring's data access exception hierarchy (e.g., DataAccessException), thus simplifying the complexity of exception handling.
Relationship to other annotations
- @Component: @Repository is a special form of the @Component annotation dedicated to the data access layer. While they can both mark classes as Spring container-managed components, @Repository provides clearer semantics and additional data access support.
- @Service and @Controller: Similar to @Repository, @Service and @Controller are extensions of the @Component annotation for the service and controller tiers, respectively. Together, they form Spring's layered architecture.
utilization
- Relational Database Access: The @Repository annotation can be applied to a DAO class that operates on a relational database, realizing database operations through JDBC, JPA, and other technologies.
- Non-relational database access: The same applies to DAO classes that operate on non-relational databases, such as MongoDB, Redis, and so on.
- Message Queue Operation: Although not common, the @Repository annotation could theoretically also be used to mark components that operate message queues, although this is more often handled by @Service or other business logic layer components.
Demo
@Repository
@Mapper
public interface UserMapper {
List<UserModel> findAll();
UserModel findByName(String username);
String findPswByName(String userName);
void save(UserModel user);
}
@Service
public class UserserviceImpl implements UserService {
@Autowired
UserMapper userMapper;
// login operation
public String login(UserModel user) {
try {
UserModel userExistN = (());
if (userExistN != null) {
String userExistP = (());
if ((())) {
return ()+"Login Successful,welcome!";
}else{
return "Login Failure,incorrect password!";
}
}else {
return "Login Failure,The user does not exist!";
}
}catch (Exception e) {
();
return ();
}
}
}
caveat
- Exception handling: Although the @Repository annotation provides an automatic exception conversion mechanism, in practice, you still need to handle exceptions appropriately according to business requirements.
- dependency injection: In classes that use the @Repository annotation, other necessary components or services are usually injected via @Autowired or other dependency injection methods.
- configure: Ensure that the appropriate auto-scanning mechanism (e.g., @ComponentScan) is enabled on the Spring configuration class or starter class so that Spring can scan for and manage these DAO components.
26. @RequestBody
A common annotation in Spring MVC and Spring Boot that is used to handle the body portion of an HTTP request. When a client sends a request to the server, the request body usually contains the data to be sent to the server. The @RequestBody annotation tells Spring's DispatcherServlet that it should bind the JSON or XML data in the request body to the parameters of the controller method.
utilization
- POST and PUT requests: In most cases, @RequestBody is used to handle POST and PUT requests, as these two request types are typically used to submit data to the server.
- Receive JSON or XML data: When a client sends data in JSON or XML format, @RequestBody helps to automatically bind this data to Java objects.
principle
When a controller method uses the @RequestBody annotation, Spring uses HttpMessageConverters to convert the data in the request body to Java objects.HttpMessageConverters are a set of classes used to convert HTTP requests and responses, and are responsible for converting the data in the request body to Java objects and the Java objects back to the response body data. HttpMessageConverters are a set of classes that convert HTTP request and response data into Java objects, and Java objects back into response body data.
By default, Spring Boot provides support for JSON and XML, so you can receive and send JSON or XML data directly. However, you can add other libraries to support other formats.
Demo
//
public class User {
private Long id;
private String name;
// an omissiongettercap (a poem)settermethodologies
}
//
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping("/add")
public ResponseEntity<String> addUser(@RequestBody User user) {
// This can be handled hereuserboyfriend,For example, saving to a database
return ("User added successfully!");
}
}
When a client sends a POST request to /users/add and the request body contains a User object in JSON format, Spring automatically converts the JSON data into an instance of the User class and passes it as an argument to the addUser method.
caveat
- Make sure that your request header (Content-Type) is correctly set to application/json or another appropriate MIME type so that Spring knows how to parse the request body.
- Spring throws an exception if the data in the request body cannot be correctly converted to a Java object (for example, if the JSON format is wrong or the fields don't match). You can catch these exceptions through global exception handling and return a friendly error message to the client.
- By default, Spring uses the Jackson library to parse JSON data. If you need to process XML data, you may need to add JAXB or other relevant dependencies.
27. @RequestMapping
A very core annotation in Spring MVC that is used to map HTTP requests to a specific handler (e.g. a method in a controller). This annotation can be declared on a class or method and defines the request URL, HTTP method (e.g. GET, POST), request parameters, request headers, and how they are mapped to a specific handler.
Main Properties
-
value / path
: Specifies the URL path of the request. This can be a specific path or a path template containing a variable (e.g. {id}). -
method
: Specifies the type of request (e.g., GET, POST). This attribute is a value from the RequestMethod enumeration or a combination of them. -
params
: Specifies the parameters that must or must not be included in the request. -
headers
: Specifies the HTTP headers that must or must not be included in the request. -
consumes
: Specifies the type of submission content (Content-Type) to process the request, such as application/json. -
produces
: Specifies the type of content to be returned, only if the (Accept) type in the request header contains the specified type.
utilization
- @RequestMapping at the class level
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Long id, Model model) {
// according to id Get user information,and populate it with model center
return "userDetail"; // Returns the view name
}
@PostMapping
public String createUser(@RequestParam String name, Model model) {
// Create User
return "userCreated";
}
}
@RequestMapping("/users") is applied to the UserController class, which means that all request URLs in this class will start with /users. Then, @GetMapping("/{id}") and @PostMapping are used to map specific HTTP GET and POST requests to different handlers, respectively.
2. @RequestMapping at the method level
@Controller
public class MyController {
@RequestMapping(value = "/hello", method = )
public String sayHello() {
return "hello"; // Returns the view name
}
@RequestMapping(value = "/goodbye", method = , params = "name")
public String sayGoodbye(@RequestParam String name) {
// Only include the 'name' Called with the
return "goodbye";
}
}
@RequestMapping is used directly on the method, specifying the URL path of the request, the HTTP method, and the request parameters. params = "name" means that the request must contain parameters named name.
28. @ResponseBody
It is used to bind the return value of the controller to the web response body. When a handler method is annotated with @ResponseBody, Spring automatically writes the method's return value to the HTTP response (HttpServletResponse). This process usually involves using Message Converters to convert the return value to an appropriate format (e.g., JSON, XML, etc.) and then writing it to the response body.
corresponds English -ity, -ism, -ization
- RESTful Web Services: @ResponseBody is useful when building RESTful Web services because it allows you to serialize objects directly to JSON or XML and send them to the client as HTTP responses.
- Ajax Requests: In Ajax requests, servers often need to return data in JSON or XML format, and @ResponseBody makes it easy to do so.
Demo
You have a User object and a controller method, and you want to return the User object to the client in JSON format.
@RestController // This is a convenient annotation that is equivalent to adding @Controller and @ResponseBody to each method
public class UserController {
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
// Assuming there is a service or DAO layer call here that returns the User object based on the id
User user = new User();
(id);
("John Doe"); // Since @Restriction is being used here, the user object will be returned.
// Since @RestController is used here, or if only this method used @ResponseBody.
// Spring will automatically serialize the User object to JSON and write it to the response body
return user; }
}
}
// If you're not using @RestController but want to apply @ResponseBody to a single method, you can do so:
@Controller
public class UserController {
@GetMapping("/user/{id}")
@ResponseBody // Tell Spring MVC what to return should be bound to the response body
public User getUserById(@PathVariable Long id) {
// ... Same as the example above
}
}
caveat
- When you use @ResponseBody, Spring looks for the appropriate HttpMessageConverter to convert your return value into the format required for the response body.
- If you are using Spring Boot and have added a Spring Web Starter dependency, Spring Boot automatically configures some of the commonly used HttpMessageConverter such as Jackson for JSON and JAXB for XML.
- @RestController is a combination annotation of @Controller and @ResponseBody for building RESTful web services. If you find that all the methods in your controller need @ResponseBody, it's cleaner to use @RestController.
29. @RestController
Spring 4.0 introduces an annotation that is a combination of the @Controller and @ResponseBody annotations. When you use the @RestController annotation on a class, it means that all methods in the class apply the effect of the @ResponseBody annotation by default, i.e., the return value of the method is automatically bound to the Web response body and is usually converted to a format such as JSON or XML (depending on the configured message converter configured).
corresponds English -ity, -ism, -ization
- RESTful Web Services: @RestController is ideal for building RESTful Web services because it simplifies the process of serializing objects to JSON or XML and sending them to the client.
- Simplified configuration: If you find that most or all of the methods in your controller class require the @ResponseBody annotation, then using @RestController reduces duplicate code and makes your controller class more concise.
Demo
@RestController
public class UserController {
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
// Assuming there's a service or DAO layer call here that returns the User object based on the id
User user = new User();
(id);
("John Doe"); // Since @RestConstructor is being used, it's a good idea to use the @RestConstructor.
// Since @RestController is used, Spring automatically serializes the User object to JSON and writes it into the response body
return user; }
}
@PostMapping("/user")
public ResponseEntity<String> createUser(@RequestBody User user) {
// Assuming there is a service layer call here to create the user
// Even though a ResponseEntity is returned here, @RestController still applies because it only cares about whether or not the return value should be written to the response body
return ("User created successfully");
}
}
The getUserById method returns a User object, while the createUser method returns a ResponseEntity.
caveat
- When you use @RestController on a class, all handlers in that class are treated as @ResponseBody methods unless you explicitly use @ResponseBody(false) at the method level to override this behavior (but usually this is not necessary).
- @RestController makes building RESTful Web services easier and more straightforward because it reduces the amount of sample code that needs to be written.
- If you need a mix of @ResponseBody and non-@ResponseBody methods in a controller class (e.g., some methods return the view name instead of the data), then you should use @Controller instead of @RestController and explicitly add the @ResponseBody where needed. annotation where needed.
30. @Async
Used to declare an asynchronous method. When you use the @Async annotation on a method, Spring executes the method asynchronously in a separate thread when it is called. This means that the caller thread doesn't need to wait for the @Async annotated method to finish executing, but can continue with other tasks.
corresponds English -ity, -ism, -ization
- Improve application performance: With asynchronous processing, it is possible to avoid blocking the main thread during the execution of long-running tasks, thus improving the responsiveness and throughput of the application.
- decoupled: Asynchronous processing can help you decouple method invocation and execution, so that the caller of a method doesn't need to care about the details of the method's execution and its execution time.
utilization
In order to use the @Async annotation, you need to fulfill the following conditions:
- Configuring Asynchronous Support: Enable asynchronous support in your Spring configuration. This can be done by adding the @EnableAsync annotation to the configuration class.
- Apply the @Async annotation to the appropriate method.: Ensure that the @Async annotation is applied to methods that are public, non-static, of a non-void return type (or CompletableFuture/Future, etc. in Java 8+), and are not modified by final.
- Return Type: Typically, @Async methods return a Future or CompletableFuture object so that the caller can check the execution status of the asynchronous method or get the result. However, it is also possible to return void or other types, but then the caller does not have direct knowledge of the asynchronous method's execution result or status.
Demo
@Configuration
@EnableAsync
public class AsyncConfig {
// Usually no beans need to be implemented here, just the @EnableAsync annotation to enable asynchronous support.
}
@Service
public class AsyncService {
@Async
public Future<String> executeAsyncTask(int number) throws InterruptedException {
// Simulation of long-running tasks
(1000);
return new AsyncResult<>("AsyncTask completed with value " + number);
}
// It is also possible to returnvoid,But then the caller won't be able to get the result of the execution
@Async
public void executeVoidAsyncTask(int number) {
// Same long-running tasks
("Executing void async task with number " + number);
}
}
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService.
@GetMapping("/async/{number}")
public ResponseEntity<String> asyncEndpoint(@PathVariable int number) throws ExecutionException, InterruptedException {
Future<String> future = (number);
// Here you can perform other tasks without waiting for the asynchronous method to complete.
String result = (); // Get the result of the asynchronous method, which will block until the asynchronous method completes.
return (result); // Get the result of the asynchronous method.
}
}
While the () method can be used to get the result of an asynchronous method execution, it blocks the calling thread until the asynchronous method completes. If you want to avoid blocking, you can use CompletableFuture and take advantage of its non-blocking API for asynchronous results.
caveat
- When you use the @Async annotation, make sure you don't call asynchronous methods in the same class because Spring's proxy mechanism (usually based on JDK dynamic proxies or CGLIB) only proxies methods that are invoked through the Spring container. If you call another method with the @Async annotation in the same class, the call will not be handled asynchronously.
- Exception handling during asynchronous method execution requires special attention. If you are using () to get the result, any uncaught exceptions thrown by the asynchronous method will be wrapped and thrown as ExecutionException. If you're using CompletableFuture, you can be more flexible with exception handling, such as specifying exception handling logic through the exceptionally method.
31. @AutoConfigureAfter
It is primarily used to indicate that a Configuration Class should be autoconfigured after the other autoconfiguration classes specified. This annotation provides a mechanism for controlling the order of Spring Boot autoconfiguration, ensuring the correctness of dependencies and thus the correctness and maintainability of the application.
corresponds English -ity, -ism, -ization
- Control of the auto-configuration sequence: In Spring Boot, there are a number of auto-configuration classes that automatically configure the system based on its environment, conditions, and so on. However, these configuration classes sometimes depend on other configuration classes. By using the @AutoConfigureAfter annotation, you can ensure that the dependent configuration classes are loaded and configured first.
- Ensure correctness of dependencies: When an autoconfigure class needs to use a bean or configuration from another autoconfigure class, using @AutoConfigureAfter avoids dependency problems caused by loading them in the wrong order.
utilization
- annotation position: The @AutoConfigureAfter annotation can only be used on configuration classes, i.e. classes modified by the @Configuration annotation.
- Parameter Specification: In the value attribute of the @AutoConfigureAfter annotation, you can specify one or more classes that must be autoconfigured after the specified autoconfiguration class.
Demo
@Configuration
@AutoConfigureAfter()
public class MyAutoConfiguration {
// ... Configuration class implementation ...
}
The MyAutoConfiguration class will be autoconfigured after the DataSourceAutoConfiguration class.
caveat
- The specified class must already exist: The class specified in the @AutoConfigureAfter annotation must have been auto-configured or explicitly defined by Spring Boot, otherwise an AutoConfigurationOrderFailedException will be thrown.
- Multiple configuration classes: If more than one autoconfigure class uses the @AutoConfigureAfter annotation, the classes will be loaded in the order specified in the annotation.
- Relationship to @AutoConfigureBefore: @AutoConfigureBefore is the counterpart of @AutoConfigureAfter and is used to indicate that an autoconfiguration class should be autoconfigured before the other autoconfiguration classes specified.
32. @Cacheable
It is mainly used for declarative caching, i.e., caching the return value of a method so that subsequent calls to the same method can fetch the result directly from the cache without having to execute the actual logic of the method again. This can significantly improve the performance and responsiveness of the system, especially when dealing with scenarios where read operations are frequent but data updates are infrequent.
corresponds English -ity, -ism, -ization
- Reduced database access: For operations that require data to be read from the database, using @Cacheable avoids repetitive database queries and reduces database stress.
- Improve performance: Reduces the consumption of computational resources by reducing the number of times a method is executed, thus improving the overall performance of the system.
utilization
Using the @Cacheable annotation in a Spring Boot project usually requires the following steps:
- Adding Dependencies: Add a Spring Boot cache starter dependency, such as spring-boot-starter-cache, to the project's files.
- Enable Cache: Add the @EnableCaching annotation to the Spring Boot startup class to enable caching support.
- Configuration Cache: Configure the type of cache (e.g. Redis, EhCache, etc.) and related properties as needed.
- Using Annotations: Add the @Cacheable annotation to methods that need to be cached and specify the name of the cache, the key generation policy, and other parameters.
parameters
- value/cacheNames: Specifies the name of the cache, either a string or an array of strings, indicating the caches into which the results of the method can be cached.
- key: Specifies the key for the cache, which can be a SpEL (Spring Expression Language) expression used to dynamically generate the key for the cache based on the method parameters. If not specified, the method's parameters are used as the key by default.
- condition: Specifies the conditions for caching, a SpEL expression that determines under what circumstances the return value of a method is cached. If not specified, all results are cached by default.
- unless: Specifies an exclusion condition for caching, also a SpEL expression, which determines the circumstances under which the method's return value will not be cached. If not specified, no results are excluded by default.
Demo
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public String getData(int id) {
// Simulation of time-consuming operations
try {
(2000);
} catch (InterruptedException e) {
();
}
// The actual data acquisition logic
return "Data for id: " + id;
}
}
The result of the getData method is cached in a cache called myCache, whose key is the method's parameter id. When the getData method is called again and passed the same id, if the corresponding result exists in the cache, the cached value is returned without executing the actual logic of the method.
caveat
- cache coherence: When using @Cacheable, you need to be concerned about the consistency of cached data. If cached data is modified externally and the system does not sense the change, this can lead to data inconsistency issues.
- cache passthrough: When querying for a non-existent data, the data will not be stored in the cache, resulting in each query penetrating to the database. Cache penetration can be avoided through mechanisms such as Bloom filters.
- Cache Avalanche: When a large number of caches expire at the same time, all requests will directly access the database, resulting in a sudden increase in database pressure. Cache avalanche can be avoided by adding a random factor when setting the expiration time of the cache, using multi-level caching, and so on.
33. @Conditional
Used to control the registration of a configuration class or the creation of a bean in a condition-based context. This annotation was introduced in Spring 4.0 as part of Spring's Conditionalized Configuration to provide a flexible way to control which configurations or beans should be included in a Spring application context.
utilization
The @Conditional annotation is often used with custom condition classes that implement the Condition interface. By implementing the matches(ConditionContext, AnnotatedTypeMetadata) method, you can define when a particular configuration class or bean should be included, which is ideal for conditionally including configurations based on the runtime environment (e.g., type of operating system, version of the JVM, availability of a particular library, etc.).
Working Principle
- define conditions: First, you need to define one or more classes that implement the Condition interface. In this class, you will implement the matches method, which returns true or false depending on the given condition.
- application condition: You can then apply the @Conditional annotation to the configuration class or bean method and specify your condition class via its value attribute. If the matches method of the conditional class returns true, the configuration class or bean will be included in the Spring application context; if it returns false, it will be ignored.
Demo
// Custom Conditional Classes
public class OnWindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// Check if the operating system isWindows
return ("").toLowerCase().contains("win");
}
}
// utilization@Conditionalannotate
@Configuration
public class AppConfig {
@Bean
@Conditional()
public MyWindowsSpecificBean myWindowsSpecificBean() {
return new MyWindowsSpecificBean();
}
}
MyWindowsSpecificBean Only if the operating system isWindowsis created and registered to theSpringapplication context。
caveat
- @Conditional can be used with @Bean, @Configuration, @Component annotations.
- Spring provides several built-in conditional annotations, such as @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, and so on, which cover most of the common conditionalized configuration needs.
- When using conditionalized configurations, care should be taken to avoid creating complex conditional logic to keep the configuration clear and maintainable.
34. @ConditionalOnBean
Conditional annotation to create the current bean only if a specific bean exists in the container This annotation is typically used in Spring Boot-based applications in conjunction with the Auto-configuration feature to conditionally register a new bean based on the application's configuration and existing beans.
utilization
@ConditionalOnBean
annotation can be applied to the @Bean method of a configuration class. The method is executed and the corresponding bean is created when the specified bean exists in the Spring container; if the specified bean does not exist, the method is ignored and no bean is created.
causality
There is a RedisTemplate bean and you only want to create the RedisOperBean if the RedisTemplate exists@ConditionalOnBean
The annotation contains several attributes to specify the details of the condition:
-
value
: Class<? >[] type that specifies the type of bean that needs to exist. -
type
: String[] type, similar to the value property, but allows the name (rather than the type) of the bean. -
annotation
: Class<? extends Annotation>[] type that specifies the type of annotation that must be present on the bean that needs to be present. -
name
: String[] type, directly specifying the name of the bean to be present. -
search
: SearchStrategy type, used to specify the strategy for searching for beans, the default is , which means searching in all bean definitions.
Demo
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate() {
// configure RedisTemplate ...
return redisTemplate;
}
@Bean
@ConditionalOnBean(name = "redisTemplate")
public RedisOperBean redisOperBean(RedisTemplate<String, Object> redisTemplate) {
// suppose that... RedisOperBean need RedisTemplate dependence
return new RedisOperBean(redisTemplate);
}
}
The @ConditionalOnBean(name = "redisTemplate") annotation on the redisOperBean method ensures that the redisOperBean method is executed only if the redisTemplate Bean exists, thus creating the RedisOperBean.
caveat
- @ConditionalOnBean, along with other conditional annotations such as @ConditionalOnMissingBean, @ConditionalOnClass, and so on, make up Spring Boot's conditionalized configuration feature, providing flexible control over bean loading.
- When using @ConditionalOnBean, you need to be careful about the order in which the beans are loaded. If the current bean depends on other beans that have not yet been loaded, this may result in unexpected behavior.
- Try to avoid creating complex conditional logic in your application to keep your configuration clear and maintainable.
35. @ConditionalOnClass
Conditional annotation. Condition when the specified class is available under the class path.
36. @ConditionalOnExpression
Conditional Annotation. Based on a SpEL expression as a judgment condition.
37. @ConditionalOnJava
Conditional annotations. Based on JVM version as a judgment condition.
38. @ConditionalOnJndi
Condition annotation. Finds the specified location under the condition that JNDI exists.
39. @ConditionalOnMissingBean
Conditional annotation. When no bean is specified in the container.
40. @ConditionalOnMissingClass
Conditional annotation. When there is no class specified under the class path.
41. @ConditionalOnNotWebApplication
Conditional Annotation. The condition that the current project is not a web project.
42. @ConditionalOnResource
Conditional annotation. Whether the class path has the specified value.
43. @ConditionalOnSingleCandidate
Conditional annotation. When the specified bean has only one in the container, the latter specifies the preferred bean although there are multiple.
44. @ConditionalOnWebApplication
Conditional Annotation. The case where the current project is a web project.
45. @ControllerAdvice
Used on classes to declare a controller construct, which also combines the @Component annotation and will automatically register as a Spring bean.
46. @Enable
Support for a feature is turned on with a simple @Enable. All @Enable annotations have an @Import annotation, @Import is used to import configuration classes, which means that these auto-enable implementations actually import some auto-configured beans (1. Direct import of configuration classes 2. Selection of configuration classes based on conditions 3. Dynamic registration of configuration classes)
47. @EnableAspectJAutoProxy
Enabling Spring Support for AspectJ
48. @EnableAsync
Enable asynchronous task support. The annotation is on the configuration class.
49. @EnableAutoConfiguration
This annotation automatically loads all the beans required by the application - this relies on Spring Boot looking in the class path. This annotation combines the @Import annotation, which imports the EnableAutoCofigurationImportSelector class, which uses methods to scan for jar packages with META-INF/ files. And in it declares what autoconfigurations are available.
50. @EnableConfigurationProperties
The annotation is on the class and the declaration turns on property injection, using @Autowired injection. Example: @EnableConfigurationProperties().
51. @EnableScheduling
annotation on the configuration class to turn on support for scheduled tasks.
52. @EnableWebMvc
Used in the configuration class, open SpringMvc Mvc some of the default configuration: such as ViewResolver, MessageConverter and so on. At the same time in their own customized SpringMvc configuration related to the need to do two things: 1. Configuration class inheritance WebMvcConfigurerAdapter class 2. is the need to use this @EnableWebMvc annotation.
53. @ImportResource
Although Spring advocates zero configuration, but still provides support for xml files, this annotation is used to load the xml configuration. Example: @ImportResource({"classpath
54. @InitBinder
Customize the WebDataBinder via the @InitBinder annotation (use it on methods that have a WebDataBinder as a parameter, use the WebDataBinder to customize the data binding within the method, e.g., you can ignore the parameter Id passed by request, etc.).
55. @Inject
Annotations provided by JSR-330
56. @PathVariable
Placed before the parameter, it is used to accept the path parameter.
57. @PostConstruct
is labeled on the method, which is executed after the constructor has finished executing.
58. @PreDestroy
Labeled on the method, the method is executed before the object is destroyed.
59. @PropertySource
Specifies the file address. Provides a convenient, declarative mechanism for adding a PropertySource to Spring's environment. used with the @configuration class. Configuration. Among the properties are value (path), produces (defines the type and character set of the returned media), and method (specifies the request method).
60. @Resource
Annotations provided by JSR-250
61. @RunWith
This is a Junit annotation, springboot integrated junit. generally used in the test class :@RunWith() - SpringJUnit4ClassRunner in the JUnit environment to provide Sprng TestContext Framework features
62. @Scheduled
Annotation on the method declares that the method is a scheduled task. Supports many types of scheduled tasks: cron,fixDelay,fixRate