Spring & Spring Boot Common Annotations Organize
Modern Spring and Spring Boot applications use a lot of annotations to simplify configuration, management of components, and implement various framework functions. This article systematically organizes commonly used Spring/Spring Boot annotations and introduces them according to functional classification. Each annotation covers its meaning, provides sources, application scenarios, and code examples to help developers understand and quickly retrieve them.
1. Spring Boot core annotations
@SpringBootApplication
Introduction: @SpringBootApplication
It is the main entrance annotation of Spring Boot applications. It is marked on the startup class, indicating that this is a Spring Boot application. This annotation is provided by Spring Boot (locatedpackage), essentially a combination annotation, containing key configuration annotations for Spring Framework and Spring Boot.
Functions and scenarios:use@SpringBootApplication
After marking the main class, Spring Boot will automatically perform the following configuration:
-
Configuration class declaration:Included
@SpringBootConfiguration
(It is@Configuration
Specialization of ) , so this class is considered a configuration class and can define beans. -
Component scan:Included
@ComponentScan
, will automatically scan the package where the class is located and its components under the subpackage (such as@Component
、@Service
、@Controller
class marked with annotation), register them as beans in Spring container. -
Automatic configuration:Included
@EnableAutoConfiguration
, automatically configure Spring Boot applications based on dependencies under the classpath. For example, if there is an HSQLDB database dependency in the classpath, the in-memory database, etc. will be automatically configured. Developers do not need to write a lot of configurations manually to launch applications.
Example of usage:Create a Spring Boot main boot class and add it to the class@SpringBootApplication
Annotation and writingmain
Method to start the application:
@SpringBootApplication public class MyApplication { public static void main(String[] args) { (, args); } }
In the above code,MyApplication
Classes by@SpringBootApplication
Annotations are marked as application portal. runAfter that, Spring Boot will boot the embedded server, initialize the Spring container, automatically scan the components and complete the configuration.
Note:@SpringBootApplication
Properties are provided for customization, such asexclude
Specific automatic configuration classes can be excluded. If you need to disable some automatic configuration, you can use e.g.@SpringBootApplication(exclude = )
To exclude.
2. Spring container and component registration notes
This type of annotation is used to register classes as components managed by Spring containers or define configurations to replace traditional XML configuration files to implement annotation-driven assembly.
@Component
Introduction: @Component
is a general component annotation provided by Spring Framework (). It is used to identify a normal Java class as in a Spring containerBean. The marked class will be discovered and instantiated when the component is scanned, and the life cycle will be managed uniformly by the container.
Functions and scenarios:When a class is not easy to classify to a specific layer, it can be used@Component
Make labels. Typical scenarios such as tool classes, general logic processing classes, etc. use@Component
After that, there is no need to declare a bean in XML, Spring will automatically register it based on the configured scan path.Provide modules:The Spring Context module provides scanning of components and@Component
Annotation support.
Example of usage:Define a component class and demonstrate injection:
@Component public class MessageUtil { public String getWelcomeMessage() { return "Welcome to Spring!"; } } //Use components@Service public class GreetingService { @Autowired private MessageUtil messageUtil; public void greet() { (()); } }
In the above example,MessageUtil
Class passed@Component
Mark as a container bean,GreetingService
Used in@Autowired
(See later) Inject it and finally call its method.
@Service
Introduction: @Service
yes@Component
A specialization of theBusiness logic layercomponent (Service layer). It is located in the Spring FrameworkBag.
Functions and scenarios:In a hierarchical architecture, the service layer class uses@Service
Annotation makes the code meaning more semantic. Despite behavioral@Component
Same (scanned to bean),@Service
Emphasize that this type of business service responsibilities.Provide modules:Spring Context, also part of the component model.
Example of usage:
@Service public class OrderService { public void createOrder(Order order) { // Business logic: Create an order } }
pass@Service
,OrderService
Will be automatically scanned and registered. Where it is needed, such as the control layer or other service layer, the Bean instance can be obtained through dependency injection.
@Repository
Introduction: @Repository
yes@Component
One of the special annotations for labelingData access layerComponents (DAO layer, or repository class). Defined in Spring FrameworkIn the package.
Functions and scenarios:DAO classes (such as classes that access databases) use@Repository
Annotations can not only be scanned as container beans, but also enableException conversionFunction. The Spring DAO layer will catch the underlying data access exception (such as JDBC'sSQLException
or JPA exception), translate it into Spring unifiedDataAccessException
system, thereby simplifying exception handling. In other words, if a class is marked as@Repository
, Spring automatically handles persistent exceptions when creating a proxy for it, converting the original exception to Spring's non-checked data access exceptions for improved robustness. Also, marked@Repository
The class can be@Autowired
Allow the annotations to be automatically assembled to other places.
Example of usage:
@Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public User findById(Long id) { try { return ("SELECT * FROM users WHERE id=?", new BeanPropertyRowMapper<>(), id); } catch (DataAccessException e) { // Spring has translated the underlying SQLException to DataAccessException throw e; } } }
In the above example,UserDao
use@Repository
Annotation, making it a DAO component for container management. Spring automatically provides exception conversion function for it: if the JDBC operation is thrownSQLException
, will be translated asDataAccessException
(RuntimeException), the call can handle it uniformly. It is also allowed to pass after marking@Autowired
Injected into the service layer for use.
@Controller
Introduction: @Controller
It is the control layer component annotation of Spring MVC, which is also derived from@Component
. Provided by the Spring Web MVC module (), used to identify a class isWeb MVC Controller, responsible for processing HTTP requests and returning views or responses.
Functions and scenarios:In a web application,@Controller
The annotated class will be recognized as a controller by the DispatcherServlet, which is used to map the request URL, encapsulate the model data, and return the view name. Usually, it returns to the page with view templates (such as Thymeleaf, JSP). If you need to return JSON data directly, you can cooperate@ResponseBody
Or use directly@RestController
(See the latter below).
Example of usage:
@Controller public class HomeController { @RequestMapping("/home") public String homePage(Model model) { ("msg", "Hello Spring MVC"); return "home"; // Return the view name, parsed into a page by the view parser } }
The aboveHomeController
use@Controller
Tag, providing a method to map “/home” requests. Return value"home"
Represents the logical name of the view, the framework will parse to the specific page according to the configuration (such as). If we use it on the class
@Controller
, the framework will automatically register the corresponding map when it is started.
@RestController
Introduction: @RestController
It is a combination annotation provided by Spring, which is equivalent to using it on the class at the same time.@Controller
and@ResponseBody
. It is mainly provided by the Spring Web module forRESTful Web Servicescontroller.
Functions and scenarios:Tag@RestController
The class is recognized as a controller, and the return value of each processing method is output directly as the HTTP response body, rather than parsing as the view name. Suitable for scenarios where data needs to be returned such as JSON, XML, etc., such as Web API interface.Module provides: Spring Web(Spring MVC)。
Example of usage:
@RestController @RequestMapping("/api") public class UserApiController { @GetMapping("/hello") public String hello() { return "Hello, RESTful"; } @PostMapping("/users") public User createUser(@RequestBody User user) { // Directly receive JSON deserialized into User object, and return after processing return (user); } }
UserApiController
use@RestController
Annotation, whose method returns string and object will be written directly to the response through the message converter (e.g. string as plain text,User
Objects are serialized to JSON). No need to add to each method@ResponseBody
, make the code more concise. Usually when developing REST APIs,@RestController
to define the controller.
@Configuration
Introduction: @Configuration
Used to declare aConfiguration class, provided by Spring Framework (). The configuration class can contain several
@Bean
Annotated method to define beans and hand them over to Spring containers to manage.@Configuration
It's also@Component
, so the configuration class will also be registered by the component scan.
Functions and scenarios:In Java Config-style applications,@Configuration
Equivalent to traditional XML configuration files. Used to define beans, set dependency injection rules, etc. Some automatic configurations of Spring Boot applications also exist in configuration classes.Provide modules: Spring Context。
Example of usage:
@Configuration public class AppConfig { @Bean public DataSource dataSource() { // Configure the data source bean, for example, using HikariCP data source HikariDataSource ds = new HikariDataSource(); ("jdbc:mysql://localhost:3306/test"); ("root"); ("123456"); return ds; } @Bean public UserService userService() { // Register UserService as a Bean and inject the dependent data source return new UserService(dataSource()); } }
The aboveAppConfig
quilt@Configuration
The annotation is identified as a configuration class. methoddataSource()
anduserService()
On@Bean
Annotations cause Spring to register its return value as a bean in the container. inuserService()
The method has been calleddataSource()
, Spring intercepts and ensures that the DataSource Bean of the singleton in the container is returned, rather than reinstanced every time (i.e.CGLIBEnhanced@Configuration
Class ensures bean singleton behavior).
@Bean
Introduction: @Bean
Annotations are used forDefine a Bean. It is marked on a method, indicating that the object returned by the method will be registered in the Spring container.@Bean
Usually cooperate@Configuration
Used by the Spring Context module.
Functions and scenarios:When defining a bean through JavaConfig, use@Bean
Alternative to traditional XML<bean>
statement. For example, scenarios such as integrating beans that integrate third-party libraries, or requiring some custom logic to be executed when creating beans.@Bean
Methods can specify a name (default is the method name), and also support settingsinitMethod
(Callback method during initialization) anddestroyMethod
(Callback method when destroyed).
Example of usage:
@Configuration public class MyConfig { @Bean(name = "customBean", initMethod = "init", destroyMethod = "cleanup") public MyComponent customBean() { return new MyComponent(); } }
In the above example,@Bean
Annotation declaredcustomBean
This bean. Called at container startupcustomBean()
Method creationMyComponent
Examples and"customBean"
Name registration.initMethod="init"
Indicates that the bean is automatically called after it is createdinit()
Method initializes;destroyMethod="cleanup"
Indicates that the container is called when it destroys the beancleanup()
method. This way, the life cycle method of a bean can be managed (similar toInitializingBean
andDisposableBean
Interface or@PostConstruct
/@PreDestroy
, see later).
@ComponentScan
Introduction: @ComponentScan
For configurationComponent scanningAnnotation of the path. Provided by Spring Context, usually with@Configuration
Use together. Its purpose is to instruct Spring to search for classes with component annotations under the specified package path and register as beans.
Functions and scenarios:By default, Spring Boot's@SpringBootApplication
It has implicitly specified to scan its package and subpacket. If you need to customize the scan scope (such as scanning components for other packages), you can use@ComponentScan
Annotations and providedbasePackages
etc. Ordinary Spring applications (non-Boot) often need to be explicitly used on the main configuration class.@ComponentScan
Specify the root package.Provide modules: Spring Context。
Example of usage:
@Configuration @ComponentScan(basePackages = {"", ""}) public class AppConfig { // ... Bean definitions }
The above configuration class passes@ComponentScan
Specify that Spring will scanand
These two packages and their sub-packages are searched for all labels
@Component
/@Service
/@Controller
and register. This allows the application's components to be organized by packages, and the scanning scope is centrally managed by the configuration.
@Import
Introduction: @Import
Annotations are used to import additional configuration classes or components into Spring containers. It is provided by Spring Context and is available in@Configuration
On a class, merge one or more configuration classes. It can also be used to introduce third-party configurations.
Functions and scenarios:When the project is split into multiple configuration classes, it can be done through@Import
Combine them. For example, separate the common configuration and introduce it in the main configuration. Spring Boot automatic configuration is also widely used internally@Import
To load the configuration class by condition.Provide modules: Spring Context。
Example of usage:
@Configuration @Import({, }) public class MainConfig { // Main configuration, imported security configuration and data configuration}
As above,MainConfig
pass@Import
ImportedSecurityConfig
andDataConfig
Two configuration classes. In this way, the beans defined in these two configuration classes will also be loaded into the container, which is equivalent to assembling multiple configuration modules together. Compared to using in XML<import>
, the annotation method is more intuitive.
Note: Many of the products provided by Spring Boot@Enable...
Annotations (for example, in the following text@EnableScheduling
etc.) It is also internally@Import
Import the corresponding configuration to achieve the enable function.
3. Dependency injection annotation
Dependency injection (DI) is one of the core mechanisms of Spring. The following annotations are used to perform bean injection and assembly in containers to resolve dependencies between beans.
@Autowired
Introduction: @Autowired
It is an automatic assembly annotation provided by Spring (), used to automatically inject dependent objects by type. It can be used on fields, setter methods, or constructors. Supported by the Spring Context module.
Functions and scenarios:Marked@Autowired
The properties or methods of Spring will automatically find matching bean injections when the container starts. Among them, presstypeMatching is the default behavior. If multiple beans of the same type are matched, you need to combine them@Qualifier
or@Primary
to disambiguate (see below). If no matching bean is found, an exception will be thrown by default. Can be set by@Autowired(required=false)
To indicate that if the bean cannot be found, the injection will be skipped without an error.
Example of usage:
@Component public class UserService { @Autowired // Automatic assembly by type private UserRepository userRepository; // Or constructor injection // @Autowired // public UserService(UserRepository userRepository) { ... } public User findUser(Long id) { return (id); } }
In the above example,UserService
Have a memberuserRepository
,use@Autowired
Mark. The container will automatically typeUserRepository
The bean is injected (assuming there is already@Repository
or@Component
TaggedUserRepository
accomplish). Developers can use it through constructors, setters, or field injection@Autowired
。Notice:Spring 4.3+ If there is only one constructor in the class and parameters need to be injected, the constructor can be omitted.@Autowired
, will still be automatically injected.
@Qualifier
Introduction: @Qualifier
Annotations and@Autowired
Used in conjunction with the dependency injection matching by name or qualifier. It is provided by Spring () can resolve conflicts when there are multiple beans of the same type in the container.
Functions and scenarios:By type injection by default cannot determine which one to inject when there are more than one candidate bean. For example, two implementation classes implement the same interface and are both registered as beans. In this case, it can be used at the injection point@Qualifier("beanName")
Specify which bean to inject, or use it at the bean definition@Component("name")
Name the bean and then reference the qualifier of the same name at the injection.Provide modules: Spring Context/Beans。
Example of usage:
@Component("mysqlRepo") public class MySqlUserRepository implements UserRepository { ... } @Component("oracleRepo") public class OracleUserRepository implements UserRepository { ... } @Service public class UserService { @Autowired @Qualifier("mysqlRepo") // Specify the implementation with the injection name mysqlRepo private UserRepository userRepository; // ... }
As above, there are twoUserRepository
Implement beans, named "mysqlRepo" and "oracleRepo" respectively. existUserService
In, by@Qualifier("mysqlRepo")
Specifies to inject a bean named mysqlRepo. This way, even if there are multiple beans of the same type, Spring can accurately inject the required dependencies.
@Primary
Introduction: @Primary
Annotations are used to mark a Bean as the primary candidate. When multiple beans appear by type injection, mark@Primary
The beans will be injected first. It is provided by Spring (), can act on a class or method (e.g.
@Bean
method).
Functions and scenarios:If it is not convenient to use at every injection point@Qualifier
Specify a bean, another way is to use it at the bean definition@Primary
Declare a preferred bean. When there is ambiguity, the container will select the tag.@Primary
bean injection. Notice,@Primary
There can only be one, otherwise it is still impossible to choose clearly.Provide modules: Spring Context。
Example of usage:
@Configuration public class RepoConfig { @Bean @Primary // Mark this bean as first choice public UserRepository mysqlUserRepository() { return new MySqlUserRepository(); } @Bean public UserRepository oracleUserRepository() { return new OracleUserRepository(); } } @Service public class UserService { @Autowired private UserRepository userRepository; // will be automatically injected into mysqlUserRepository as it is marked @Primary}
In the configuration of the above example, we define twoUserRepository
Bean, where the MySQL implementation is marked as@Primary
. Therefore, inUserService
Inject by typeUserRepository
Spring will inject markers@Primary
MySQL implementation.@Primary
Provides a global default scheme that simplifies the selection of injection points.
@Resource
Introduction: @Resource
is annotation from the JSR-250 specification (Javax/Jakarta Annotation) that Spring provides support for injecting dependencies by name or by type. It is usually located(Java EE/Jakarta EE) package.Notice:Although not in the Spring package, the Spring container can recognize and process it.
Functions and scenarios: @Resource
It can be regarded as a function similar to@Autowired + @Qualifier
a combination of . By default, pressnameInjection: It first looks for beans in the container by the attribute name or specified name, and then matches by type if it cannot be found. This is useful in some cases, such as when it needs to be compatible with traditional Java EE code. In Spring applications, some developers prefer to use it@Resource
Perform dependency injection.Provide modules:The corresponding Jakarta Annotation API needs to be introduced, but Spring Framework itself supports processing.
Example of usage:
@Component("userRepo") public class UserRepositoryImpl implements UserRepository { ... } @Service public class UserService { @Resource(name = "userRepo") // Inject a Bean named "userRepo" by name private UserRepository userRepo; // ... }
here,UserRepositoryImpl
The component is named"userRepo"
. existUserService
In, by@Resource(name = "userRepo")
Come inject. If omittedname
property,@Resource
By default, attribute nameuserRepo
Lookup as bean name. and@Autowired
different,@Resource
Not supportedrequired=false
attribute, but its exception information may be more intuitive (throw it if the bean cannot be foundNoSuchBeanDefinitionException
). It is worth mentioning that Spring also supports JSR-330@Inject
() annotation, its semantics and@Autowired
Similarly, it can also be used for constructor injection, etc. In actual development, you can choose to use Spring native according to team specifications@Autowired
Still standard@Resource
/@Inject
。
@Value
Introduction: @Value
Annotations are used to inject property values from externalized configurations into fields or parameters of beans. It is provided by Spring (), which is often used to read /yaml configuration files or system environment variables, JNDI and other attributes.
Functions and scenarios:When you need to use the values in the configuration file in a bean, you can use@Value("${}")
injection. For example, database connection parameters, service port number, etc. Setting default values and SpEL expressions are also supported.Provide modules:Spring Context Environment abstraction.
Example of usage:
Assume there is the following content:
=MySpringApp =1.0.0
Java class usage@Value
injection:
@Component public class AppInfo { @Value("${}") private String appName; @Value("${:0.0.1}") // With default value, if the configuration is missing, use 0.0.1 private String appVersion; // ... }
The aboveAppInfo
In the category,@Value("${}")
Will put the configurationValue injected into
appName
Field. If the corresponding attribute does not exist, the startup will fail. andappVersion
Fields provide default values0.0.1
, when the configuration file is not setThe default value will be used. This allows for flexibility to decouple external configuration from the code, making it easier for applications to adjust parameters without changing the source code.
@Scope
Introduction: @Scope
Annotations are used to specify the scope of a bean, provided by Spring (). By default, beans in Spring containers are singleton scoped. pass
@Scope
Other scopes can be defined, such as prototype, request, session, etc.
Functions and scenarios:Common scopes:
-
singleton
(Default): Only one instance is maintained in the container. -
prototype
: A new instance is created every time a bean is requested. - Web-related scope (need to be used in a web container environment):
request
(Create each HTTP request),session
(Create per session) etc.
In scenarios where new objects are needed (such as stateful beans), the bean can be defined as prototype; in a web application, some beans want to survive with requests or sessions, and the corresponding scope can be used.Provide modules: Spring Context。
Example of usage:
@Component @Scope("prototype") public class Connection { public Connection() { ("New Connection created."); } }
WillConnection
Bean is declared as prototype, and a new instance is created every time it is retrieved:
@Autowired private Connection conn1; @Autowired private Connection conn2;
aboveconn1
andconn2
Will be different instances becauseConnection
Defined as prototype. The log will be printed twice "New Connection created." If the scope is singleton, the instance is created only once and reused. It should be noted that the life cycle of a prototype bean is managed by the user, and Spring is only responsible for creating it and will not automatically call its destruction method.
@Lazy
Introduction: @Lazy
Annotations are used to delay initialization of a bean until first use (lazy loading). Provided by Spring (), can be used at class level or
@Bean
Method.
Functions and scenarios:By default, a singleton bean is initialized when the container starts. If some beans are time-consuming to create or may not be used during the application run, they can be marked as@Lazy
, this will be instantiated only when it is really needed, reducing startup time and resource consumption. Lazy loading is often used for example: debugging or reducing unnecessary bean creation in unit tests, or avoiding the suspension of injection initialization of beans when cyclic dependencies. For prototype beans, Spring always delays creation (because it is created on demand).@Lazy
Mainly targeting singleton beans.Provide modules: Spring Context。
Example of usage:
@Service @Lazy public class HeavyService { public HeavyService() { // Constructors may be initialized in large quantities ("HeavyService initialized"); } // ... } @Controller public class DemoController { @Autowired private HeavyService heavyService; // Tagged by @Lazy and will not be instantiated when container starts // ... }
As above,HeavyService
use@Lazy
Annotations are marked as lazy loading singletons. "HeavyService initialized" will not be printed on startup. whenDemoController
The first actual callheavyService
Spring will only create a method or access itHeavyService
Instance and inject. This is helpful for optimizing startup performance and loading components on demand. However, lazy loading should be used with caution. If the bean is used immediately after startup, the initialization should not be delayed to avoid delays during the first call.
4. Configuration attribute annotation
Spring provides a mechanism to bind configuration file content to objects. This type of annotation helps manage the external configuration and environment distinction of applications.
@ConfigurationProperties
Introduction: @ConfigurationProperties
Used to map a set of configuration properties to a Java class. Provided by Spring Boot (), usually used with beans. Bulk inject configuration items into the properties of the class through prefix (prefix).
Functions and scenarios:When there are multiple related configurations that need to be used, it is better to use them one by one@Value
, you can define a configuration property class. For example, application configuration, data source configuration, etc. Tag on class@ConfigurationProperties(prefix="xxx")
After that, the attributes of this class will be assigned values according to the prefix to read the corresponding items in the configuration file. This class needs to be registered as a bean (can be added on the class@Component
Or in configuration class@Bean
Created), Spring Boot will automatically bind the configuration to the bean instance.
Example of usage:
:
app: name: MyApp apiUrl: pool: size: 20 enableLog: true
Define attribute binding class:
@Component // Make sure to be scanned and registered as a Bean@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private String apiUrl; private Pool pool; // Internal static classes or ordinary classes are used for nested properties public static class Pool { private int size; private boolean enableLog; // getters/setters ... } // getters/setters ... }
WillAppProperties
Injection use:
@RestController public class AppInfoController { @Autowired private AppProperties appProperties; @GetMapping("/appInfo") public AppProperties getAppInfo() { // Return the entire configuration object, the framework will be serialized to JSON return appProperties; } }
In this example,@ConfigurationProperties(prefix="app")
Make YAML inapp
The configuration under the following is automatically bound toAppProperties
Bean。name
、apiUrl
Will be assigned correspondingly, nestedand
Injected into
Pool
in class. This allows easy management and verification of grouped configuration properties. It should be noted that the binding class must have a parameter constructor and provide a standard getter/setter. Spring Boot also supports JSR-303 verification annotation (such as @Validated)@ConfigurationProperties
Verify the configuration format.
@EnableConfigurationProperties
Introduction: @EnableConfigurationProperties
Yes Spring Boot is used to enable@ConfigurationProperties
Supported annotations. It is usually added to the main application class or configuration class to use it to bring@ConfigurationProperties
The annotated configuration POJO is injected into the container.
Functions and scenarios:After Spring Boot, if the configuration property class has been declared as a bean (for example, added@Component
), there is no need to use this annotation explicitly.@EnableConfigurationProperties
Commonly used when you need to include configuration property classes that are not scanned by components into Spring management. For example, if you define a pure POJO without @Component, you can specify a list of configuration classes to enable binding via this annotation on the main class.Provide modules: Spring Boot AutoConfigure。
Example of usage:
@SpringBootApplication @EnableConfigurationProperties() public class MyApplication { // ... }
The above is added to the main startup class@EnableConfigurationProperties()
, explicitly specify thatAppProperties
This one is@ConfigurationProperties
The annotated class is incorporated into the configuration property binding and registered as a bean. This way, even if it is not added@Component
, still available@Autowired
injectionAppProperties
Example. The Spring Boot automatic configuration module scans this annotation and completes the corresponding binding work.
@Profile
Introduction: @Profile
Annotations are used to load beans based on the ** environment (Profile). Provided by Spring (). Can be labeled on a class or method (Bean method), and the bean will be registered to the container only if the activated environment matches the specified Profile.
Functions and scenarios:Commonly used to distinguish configurations from development, testing and production environments. For example, if the development environment uses an embedded database, and the production environment uses a formal database connection, you can use it@Profile("dev")
and@Profile("prod")
Annotations label different configuration classes or beans separately. Configure when running the applicationActivate a Profile and the corresponding bean takes effect.Provide modules:Spring Context Environment Management.
Example of usage:
@Configuration public class DataSourceConfig { @Bean @Profile("dev") public DataSource memoryDataSource() { // The development environment uses an in-memory database return new H2DataSource(...); } @Bean @Profile("prod") public DataSource mysqlDataSource() { // Use MySQL data source in the production environment return new MySQLDataSource(...); } }
When setting=dev
When the application starts, only the application will be createdmemoryDataSource
Bean; set toprod
Create only whenmysqlDataSource
Bean. If no Profile is activated, neither of the above two beans will be loaded (can also be used@Profile("default")
Specify the default configuration). use@Profile
It realizes the registration of beans according to the environment conditionally, which facilitates the operation of one set of codes in multiple environments.
5. Bean life cycle and scope annotations
Spring-managed beans have a full life cycle, including initialization and destruction processes. The following annotations are used to execute methods at specific stages of the life cycle and to control the scope and loading timing of the bean.
@PostConstruct
Introduction: @PostConstruct
is an annotation from the Java standard (JSR-250) (located). After the Spring container initializes the dependency injection, it will call the method marked by the annotation. Commonly used for initialization logic. It is important to note that in Spring Boot 3+,
@PostConstruct
etc. were introduced by Jakarta and needed corresponding dependencies.
Functions and scenarios:When we want to automatically execute some initialization code after the bean completes dependency injection, we can add it to the bean's method@PostConstruct
. For example, set default values, turn on timers, check configuration integrity, etc. In traditional Spring, this is equivalent to<bean init-method="...">
Or implementInitializingBean
InterfaceafterPropertiesSet
。Provide modules:JSR-250 (Javax/Jakarta Annotation), called by Spring container support.
Example of usage:
@Component public class CacheManager { private Map<String, Object> cache; @PostConstruct public void init() { // Initialize cache cache = new ConcurrentHashMap<>(); ("CacheManager initialized"); } }
When Spring createsCacheManager
After injecting the dependency, it will be called automaticallyinit()
Method, output "CacheManager initialized" and complete cache container initialization. In this way, the developer does not need to manually call the initialization logic, and the container hosting is completed. This is very convenient for singleton beans.
@PreDestroy
Introduction: @PreDestroy
Also from JSR-250 standard (), Spring calls the method that labels the annotation before the bean is destroyed (before the container is closed or the bean is removed). Commonly used for resource release, state saving and other operations.
Functions and scenarios:When the application is finished or the container is about to destroy the bean, you want to perform some cleaning work, such as closing file flow, thread pool, database connection, etc., you can add it to the method@PreDestroy
annotation. Equivalent to XML configuration<bean destroy-method="...">
Or implementDisposableBean
Interfacedestroy
method.Provide modules:JSR-250, called by the Spring container.
Example of usage:
@Component public class ConnectionManager { private Connection connection; @PostConstruct public void connect() { // Establish a database connection connection = (...); } @PreDestroy public void disconnect() throws SQLException { // Close the database connection if(connection != null && !()) { (); ("Connection closed."); } } }
In the above example,ConnectionManager
The bean establishes a database connection during initialization, and passes through the container when it is destroyed.@PreDestroy
Taggeddisconnect()
Method to close the connection. Spring calls this method when the application is closed to ensure resource release. This makes resource management more reliable and avoids problems such as connection leakage.
@Scope
(Scope) – See Part 3 above
(Brief description here:)@Scope
Annotations can change the scope of a bean, for example"singleton"
、"prototype"
wait. Its use has been described in detail in the Dependency Injection section.
@Lazy
(Lazy Loading) – See Part 3 above
(Brief description here:)@Lazy
The initialization of the bean can be delayed until the first use. Improve startup performance or solve circular dependencies in some scenarios. The concepts and examples have been introduced in the previous article.
6. Web development annotations
The Spring MVC framework provides a large number of annotations to simplify web development, including request mapping, parameter binding, response processing, etc. Most of these annotations are locatedIn the package.
@RequestMapping
Introduction: @RequestMapping
It is the most basic request mapping annotation, used to map the HTTP request URL path to the corresponding controller class or processing method. Provided by Spring Web MVC. Available for class and method levels.
Functions and scenarios:Tag on class@RequestMapping("basePath")
You can specify a basic path for the controller, the method@RequestMapping("subPath")
It is further subdivided based on the classpath. It supports setting properties such as request methods (GET, POST, etc.), request parameters, and request headers, for more precise mapping of requests. For example, only GET requests are processed, or a request parameter is matched only if it exists. Spring MVC starts up to establish a URL-to-method mapping relationship based on these annotations.
Example of usage:
@Controller @RequestMapping("/users") public class UserController { @RequestMapping(value = "/{id}", method = ) public String getUserProfile(@PathVariable Long id, Model model) { // Query the user based on id... ("user", (id)); return "profile"; } @RequestMapping(value = "", method = , params = "action=register") public String registerUser(UserForm form) { // Handle user registration (form); return "redirect:/users"; } }
UserController
On the class@RequestMapping("/users")
The base path "/users" is specified. Method level annotation:
-
getUserProfile
: Map GET request to "/users/{id}". usemethod =
The request method is limited to GET.@PathVariable
Get the URL{id}
part. Return to the view name "profile" for displaying user information. -
registerUser
: Map POST requests to "/users" and useparams="action=register"
Further restrict only request parameters includeaction=register
This method is called only when it is called. This is how to distinguish different operations of the same path. Redirect to the user list after processing.
@RequestMapping
Very flexible, its commonly used properties:
value
orpath
: The mapped URL path, which can be an Ant style pattern (such as/users/*
)。method
: Limited HTTP methods, such aswait.
params
: Specify the parameter or parameter value that must exist, such as"action=register"
or"!admin"
(The admin parameter must not be included).headers
: Specify the required request header, such as"Content-Type=application/json"
。 @GetMapping
/ @PostMapping
wait
Introduction: @GetMapping
and@PostMapping
yes@RequestMapping
derived annotations specifically used to simplify mapping of GET and POST requests. Something similar@PutMapping
、@DeleteMapping
、@PatchMapping
, corresponding to the HTTP PUT/DELETE/PATCH methods respectively. They are provided by Spring MVC and are introduced starting with Spring 4.3.
Functions and scenarios:These annotations are equivalent to@RequestMapping(method = )
shortcuts to make the code more concise. Especially when defining RESTful APIs, different HTTP methods are often used to represent different operations, and these annotations can intuitively reflect the purpose of the method. For example@GetMapping
Indicates obtaining resources,@PostMapping
Indicates creating resources, etc.
Example of usage:
@RestController @RequestMapping("/items") public class ItemController { @GetMapping("/{id}") public Item getItem(@PathVariable Long id) { return (id); } @PostMapping("") public Item createItem(@RequestBody Item item) { return (item); } @DeleteMapping("/{id}") public void deleteItem(@PathVariable Long id) { (id); } }
In the above example:
-
@GetMapping("/{id})
Equivalent to@RequestMapping(value="/{id}", method = )
, used to obtain the Item of the specified ID. -
@PostMapping("")
Equivalent to classpath/items
POST request under (create a new Item), the request body passes@RequestBody
Resolved asItem
Object. -
@DeleteMapping("/{id}")
Handle the deletion operation.
These combined annotations make the controller method definition more intuitive and more RESTful. You can use the corresponding HTTP method annotation as needed. When no parameters are provided,@GetMapping
The path to the annotation can be written directly in the annotation brackets (as above@PostMapping("")
Refers to the current path).
@PathVariable
Introduction: @PathVariable
Used to bind dynamic parts of the URL path to method parameters. Provided by Spring MVC. Often with@RequestMapping
or@GetMapping
etc. used together to handle RESTful style URLs.
Functions and scenarios:When the URL contains variable placeholders (such as/users/{id}
) can be added to the method parameters@PathVariable
to get the value of the placeholder. You can specify a name to match a placeholder, or if you do not specify a name, it will be automatically inferred based on the parameter name. Suitable for scenarios where resource identification (ID, name, etc.) is obtained from the path.
Example of usage:
@GetMapping("/orders/{orderId}/items/{itemId}") public OrderItem getOrderItem( @PathVariable("orderId") Long orderId, @PathVariable("itemId") Long itemId) { return (orderId, itemId); }
When request is received/orders/123/items/456
hour:
-
orderId
The parameters will be assigned as123
(Long type conversion), -
itemId
Parameter assignment as456
。
@PathVariable("orderId")
Specify the name in the{orderId}
Placeholder corresponds. If the method parameter name is the same as the placeholder name, it can be abbreviated as@PathVariable Long orderId
。
pass@PathVariable
We don't need toHttpServletRequest
Manually parsing the path, Spring MVC automatically completes conversion and injection, simplifying the code.
@RequestParam
Introduction: @RequestParam
Used to bind HTTP requestsQuery parameters or form dataOn method parameters. Provided by Spring MVC. Supports setting default values and required attributes for parameters.
Functions and scenarios:Query string parameters (URL) that handle GET requests?
When the fields submitted by the POST form can be used@RequestParam
Get it. For example, search interface keywords, page number and size of pagination, etc. It can convert request parameters of String type to the desired target type (such as int, boolean), automatically perform type conversion and necessary verification.
Example of usage:
@GetMapping("/search") public List<Product> searchProducts( @RequestParam(name="keyword", required=false, defaultValue="") String keyword, @RequestParam(defaultValue="0") int pageIndex, @RequestParam(defaultValue="10") int pageSize) { return (keyword, pageIndex, pageSize); }
When requested/search?keyword=phone&pageIndex=1
Upon arrival:
-
keyword
Parameter bound to methodkeyword
parameter. If not provided, use the default value empty string. -
pageIndex
Bind to integer parameters, default 0 if not provided. -
pageSize
This request is not provided, so the default value is 10.
@RequestParam
Common properties:
-
value
orname
: Parameter name, corresponding to parameter name in the URL. -
required
: Whether it must be provided, default true (if it does not provide it will cause an error). In the above example, we marked keyword as false optional. -
defaultValue
: If the request does not contain this parameter, the default value will be used (note that even if the flag requires=true, there will be no error if defaultValue is marked).
pass@RequestParam
, the method can directly obtain the parsed parameter values without having to obtain and convert from request by itself, greatly simplifying the controller code.
@RequestBody
Introduction: @RequestBody
Used to convert the contents of the HTTP request message body into Java objects and bind to method parameters. Commonly used to handle request bodies such as JSON or XML. Provided by Spring MVC.
Functions and scenarios:In the RESTful API, requests such as POST/PUT usually carry data in JSON format as the request body. use@RequestBody
Annotation On method parameters (usually a custom DTO class), Spring MVC will use HttpMessageConverter to convert JSON/XML and other objects into corresponding object instances on demand. Suitable for scenarios where complex objects need to be retrieved from the request body. Corresponding to it, use it on the return value or method@ResponseBody
(or@RestController
) can serialize objects into responses.
Example of usage:
@PostMapping("/users") public ResponseEntity<String> addUser(@RequestBody UserDTO userDto) { // userDto has automatically bound the data requesting JSON (userDto); return ("User added successfully"); }
Assume that the client sends a POST request to/users
, the request body is:
{ "name": "Tom", "email": "tom@" }
Spring MVC will@RequestBody UserDTO userDto
:
- Read the request body JSON,
- Convert it to
UserDTO
Object (requires appropriate properties and setters). - Then pass it to the controller method for use.
The method returns a successful response after processing. use@RequestBody
, developers do not need to manually parse JSON, which improves development efficiency and reduces errors.
Notice:@RequestBody
The request body is required by default, otherwise an error will be reported. If you want to process null when the request body is empty, you can setrequired=false
. For GET requests, it is not generally used.@RequestBody
(GET has no subject or subject is ignored).
@ResponseBody
Introduction: @ResponseBody
Annotations are used to output the return value of the controller method directly as the content of the HTTP response instead of resolving to the view name. Provided by Spring MVC. You can be labeled on a method or (less often) on a class (labeling on a class is equivalent to applying this behavior to all methods of that class).
Functions and scenarios: @ResponseBody
It is often used in AJAX interface or RESTful methods, and needs to return JSON, XML or plain text to the client, not the page. When the method annotates this annotation, Spring converts the return object to JSON/XML or other formats to write to the response stream through the appropriate HttpMessageConverter. For example, returning an object will be automatically serialized to a JSON string.@RestController
The annotation actually contains@ResponseBody
Effect, so use@RestController
There is no need to label this annotation on each method again.
Example of usage:
@Controller public class StatusController { @GetMapping("/ping") @ResponseBody public String ping() { return "OK"; } @GetMapping("/status") @ResponseBody public Map<String, Object> status() { Map<String, Object> info = new HashMap<>(); ("status", "UP"); ("timestamp", ()); return info; } }
For the above example:
-
/ping
The request returns plain text "OK" to the client. -
/status
The request returns a map, which Spring will convert to JSON, such as:{"status":"UP","timestamp":1638346953000}
。
Because it is used@Controller
class, so you need to add it on each method@ResponseBody
to indicate the content directly. If used instead@RestController
Then these annotations can be omitted.@ResponseBody
Commonly used for quick testing interfaces or when precise control of output content is required.
@CrossOrigin
Introduction: @CrossOrigin
Annotations are used to configure cross-domain resource sharing (CORS). Provided by Spring Web and can be annotated on a class or method. It allows clients from different domain names to access the annotated resource.
Functions and scenarios:When the current and backend belong to different domains (for example, the front-end React development server http://localhost:3000 and the back-end http://localhost:8080), the browser intercepts cross-domain requests. use@CrossOrigin
You can specify cross-domain sources, methods, header information, etc. that allow cross-domain to allow calls to the browser. Different cross-domain policies can be configured uniformly for the entire controller class (noted on the class) or for a specific method (noted on the method).
Example of usage:
@RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:3000") public class ApiController { @GetMapping("/data") public Data getData() { ... } @PostMapping("/submit") @CrossOrigin(origins = "", methods = ) public void submitData(@RequestBody Data data) { ... } }
marked on the class@CrossOrigin(origins = "http://localhost:3000")
Indicates that it is allowed fromhttp://localhost:3000
Cross-domain requests access to all interfaces of the controller.submitData
A different method is marked separately@CrossOrigin
, means for/api/submit
Interface, allowed fromPOST requests cross-domain access (not subject to common configuration on the class).
@CrossOrigin
You can also set the allowed request header, whether to send credentials, etc., through parameters such asallowedHeaders
, allowCredentials
etc. Using this annotation, developers do not have to configure it in the global web configurationCorsRegistry
, cross-domain policies can be managed nearby.
@ExceptionHandler
Introduction: @ExceptionHandler
Used to define in the controllerException handling methodannotation. Provided by Spring MVC. By specifying the type of exception to be processed, when the controller method throws the exception, it is marked@ExceptionHandler
method to handle.
Functions and scenarios:To avoid exposing the exception stack to the client or writing duplicate try-catch in each controller method, you can use@ExceptionHandler
Centralized processing. For example, handling form verification exceptions returns friendly error messages, handling global exceptions returns unified format responses, etc.@ExceptionHandler
Usually with@ControllerAdvice
(Described later) It is used for global exception handling; special exception handling methods can also be defined directly within this controller.
Example of usage:
@Controller @RequestMapping("/orders") public class OrderController { @GetMapping("/{id}") public String getOrder(@PathVariable Long id, Model model) { Order order = (id); if(order == null) { throw new OrderNotFoundException(id); } ("order", order); return "orderDetail"; } // This controller specializes in handling OrderNotFoundException @ExceptionHandler() public String handleNotFound(OrderNotFoundException ex, Model model) { ("error", "The order does not exist,ID=" + ()); return "orderError"; } }
existOrderController
middle,getOrder
Method If the order cannot be found, a custom one will be thrown.OrderNotFoundException
. Use below@ExceptionHandler()
MarkedhandleNotFound
Method to handle this exception: When the exception is thrown, the controller will not continue to execute the original process, but will enter the method. Methods can receive exception objects, andModel
etc., and return a view name after processing"orderError"
Displays an error message.
pass@ExceptionHandler
, the exception handling logic inside the controller is decoupled from the normal business logic, and the code is clear and easy to maintain.
@ControllerAdvice
Introduction: @ControllerAdvice
Is a global controller enhanced annotation. Provided by Spring MVC to define aGlobal exception handling or global data bindingfacet type. The class that annotates this annotation can contain multiple@ExceptionHandler
Method, used to handle exceptions thrown by all controllers of the application; it can also include@ModelAttribute
or@InitBinder
The method is effective for all controllers.
Functions and scenarios:When certain logic needs to be handled uniformly for all controllers, use@ControllerAdvice
Very convenient. Typical usage is combination@ExceptionHandler
AsGlobal exception handler, for example, intercept allException
Returns a general error response, or classifies different exception types and returns different status codes.Provide modules: Spring MVC。
Example of usage:
@ControllerAdvice public class GlobalExceptionHandler { // Fallback for handling all exceptions @ExceptionHandler() @ResponseBody public ResponseEntity<String> handleException(Exception ex) { // Logging (); // Return a general error response return (HttpStatus.INTERNAL_SERVER_ERROR) .body("Internal Server Error: " + ()); } // Handle specific exceptions @ExceptionHandler() @ResponseBody public ResponseEntity<List<String>> handleValidationException(MethodArgumentNotValidException ex) { List<String> errors = ().getAllErrors() .stream() .map(ObjectError::getDefaultMessage) .collect(()); return ().body(errors); } }
GlobalExceptionHandler
Class use@ControllerAdvice
After the declaration, Spring will mark it@ExceptionHandler
The method applied to the controller of the entire application:
- The first method catches all exceptions that are not handled more specifically by other, prints the stack Trace and returns a 500 error message.
- The second method specifically deals with parameter verification failure exceptions, extracts the error message list and returns the 400 status and error list.
In addition, it can@ControllerAdvice
Definition in class@ModelAttribute
Method, add model data (such as public drop-down options) to all controller requests, or define@InitBinder
Methods, register global attribute editor, etc.@ControllerAdvice
Controllers that can only be applied to certain packages or annotations can be restricted by attributes, but global exception handling is usually applied globally.
pass@ControllerAdvice
, We have implemented AOP-style global controller logic extraction, so that each controller pays attention to its own business, centralizes the general logic, and keeps the code neat.
7. Data access and transaction annotations
When using Spring to manage data persistence layer, annotation definition entities such as JPA/Hibernate, as well as transaction management annotations provided by Spring, etc. will be involved.
@Entity
Introduction: @Entity
is annotation of the Java Persistence API (JPA) (), used to declare a class as a JPA entity. Spring Boot usually operates databases through JPA/Hibernate, so it is used when defining models.
@Entity
The annotated class corresponds to a table in the database.
Functions and scenarios:Tagged as@Entity
The class will be managed by a JPA implementation (such as Hibernate), and its instances can be mapped to the database record. The primary key must be provided (using@Id
Mark), optionally@Table
Specify the table name, if not, the default table name is the class name.Provide modules:JPA specification, implemented by Hibernate, etc. In Spring Boot,spring-boot-starter-data-jpa
Will automatically scan@Entity
class and create a table structure (combined with DDL generation strategy).
Example of usage:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = ) private Long id; // Primary key @Column(name = "username", length = 50, nullable = false, unique = true) private String username; // Username column @Column(nullable = false) private String password; // Password column // getters & setters ... }
User
Class@Entity
Annotations are marked as persistent entities, corresponding to database tablesusers
(Specified by @Table, if the default table name is not specifiedUser
). On the field:
-
id
use@Id
Identification as primary key,@GeneratedValue
Specify the primary key generation strategy (self-increment). -
username
use@Column
Refine Mapping: The column name is specified as username, length 50, non-empty and unique. -
password
Only used@Column(nullable=false)
, the column name defaults to the attribute name.
After defining the entity, you can use the Spring Data JPA's repository interface to automatically generate common queries (see below@Repository
and@Query
). If DDL-auto is enabled when Spring Boot is started, the table structure will be automatically created or updated in the database according to the entity definition.
@Table
Introduction: @Table
Yes JPA annotation (),Cooperate
@Entity
Use it to specify the database table information of the entity map, such as table name, schema, catalog, etc.
Functions and scenarios:By default, the entity class name is the table name. If the database table name is different from the class name, or if the schema needs to be defined, use@Table
Annotations are very necessary. Unique constraints can also be defined.Provide modules: JPA。
Example of usage:
@Entity @Table(name = "T_USER", schema = "public", uniqueConstraints = { @UniqueConstraint(columnNames = "email") }) public class User { // ... }
This entity specifies that the mapping topublic
In modeT_USER
and declareemail
There are unique constraints on the column.@Table
Properties:
-
name
: Table name. -
schema
/catalog
: The name of the schema or catalog. -
uniqueConstraints
: Unique constraint definition.
@Id
Introduction: @Id
Yes JPA annotation (), specify the primary key field of the entity class. Each
@Entity
Must have and only one attribute to use@Id
annotation. Can cooperate@GeneratedValue
Use together to define primary key generation strategies.
Functions and scenarios:After marking the primary key, JPA will use the field as the primary key column of the database table. Supports basic types or wrapper types, orwait.Provide modules: JPA。
Example of usage:
@Entity public class Product { @Id @GeneratedValue(strategy = ) private Long id; // ... Other fields}
As above,id
Fields are primary keys, and use automatic generation policies. CommonGenerationType
:
-
IDENTITY
: Database self-increment field (MySQL's AUTO_INCREMENT, etc.). -
SEQUENCE
: Use database sequences (sequences need to be defined, which are applicable to Oracle and other DBs). -
AUTO
: Let JPA automatically select the appropriate policy. -
TABLE
: Use a database table to simulate a sequence.
@GeneratedValue
Introduction: @GeneratedValue
Yes JPA annotation (),and
@Id
Used in conjunction, indicates how primary keys are generated. Specify policiesstrategy
and generatorgenerator
。
Functions and scenarios:Select the primary key generation strategy based on the database and requirements. For example, MySQLIDENTITY
Let the database be increased by itself, Oracle usesSEQUENCE
Specify the sequence name, etc.Provide modules: JPA。
Example of usage:
@Id @GeneratedValue(strategy = , generator = "user_seq") @SequenceGenerator(name = "user_seq", sequenceName = "user_sequence", allocationSize = 1) private Long id;
In the above example, use the sequence generator:
-
@SequenceGenerator
Defines a sequence generator named "user_seq" to map the database sequence "user_sequence". -
@GeneratedValue
Reference the generator and use the SEQUENCE policy. Each time User is inserted, the next value is obtained from the sequence as the ID.
For common AUTO or IDENTITY strategies, in most cases, simply label@GeneratedValue(strategy = )
etc, no additional generator configuration is required.
@Column
Introduction: @Column
Yes JPA annotation (), used to define the mapping details of entity fields and database table columns. It can be not used. If not marked, JPA maps column names by attribute name by default (lowercase underscore conversion may be performed, depending on the implementation).
Functions and scenarios: @Column
You can specify constraints such as column name, data type length, whether NULL is allowed, and whether unique is allowed. For date and time types, you can also specifycolumnDefinition
orTemporal
etc. Control SQL type.Provide modules: JPA。
Example of usage:
@Column(name = "email", length = 100, nullable = false, unique = true) private String email;
As above, turn the fieldemail
Map to a column named email (actually the same name as default, but explicitly stated), length 100, non-empty and unique. use@Column
The entity and database fields can be clearly corresponded.
@Repository
– See Part 2 above
(Additional here:) In the data access layer,@Repository
The annotated interface or class is usually used with Spring Data JPA. Like an interfaceUserRepository extends JpaRepository<User, Long>
Add@Repository
(In fact, Spring Data JPA's interface already has this semantics implicitly), Spring will generate implementations for it and hand them over to the container for management.@Repository
There are no other method properties in itself except for providing component scanning and exception conversion.
@Transactional
Introduction: @Transactional
It is a declarative form provided by SpringTransaction Managementannotation(). It can be labeled on a class or method, indicating that the database operations in it should be executed in a transaction. Spring will provide transaction support at runtime, such as starting, committing, or rolling back transactions.
Functions and scenarios:Database operations require transactions to ensure data consistency. For example, updating multiple tables at the same time, either all succeed or all fail. use@Transactional
It can be handled automatically by the framework without manually programming the transaction. Typical Applications:
- The Service layer method requires atomicity, then
@Transactional
, Spring will start the transaction when entering the method. If the method returns successfully, it will be submitted. If there is an exception, it will be rolled back. - It can also be added to the class to indicate that all public methods in the class are transactionally managed.
Provide modules:The Spring ORM/Transaction module requires the corresponding transaction manager (DataSourceTransactionManager or JpaTransactionManager, etc.). Spring Boot automatically configures the appropriate transaction manager based on the data source.
Example of usage:
@Service public class AccountService { @Autowired private AccountRepository accountRepo; @Autowired private AuditService auditService; @Transactional public void transfer(Long fromId, Long toId, BigDecimal amount) { // Deduct the transfer account balance (fromId, amount); // Increase the balance of transfer to the account (toId, amount); // Record the transfer flow (fromId, toId, amount); // When the method ends, Spring automatically submits the transaction. If a runtime exception occurs, it will automatically roll back. } }
transfer
Method marked@Transactional
, so the above three database operations will be in the same transaction: if any step throws an uncaught exception (only RuntimeException and Error by default will cause a rollback, it can be passedrollbackFor
(Properties change rollback rules), all executed database updates will be rolled back to maintain data consistency. If all succeed, the transaction is committed and the true persistence will be updated.Transaction communication behaviorandIsolation leveletc. can also be configured by annotation attributes, for example@Transactional(propagation=Propagation.REQUIRES_NEW)
Start a new transaction,@Transactional(isolation=)
Set high isolation levels, etc., depending on business needs.
Note: Use@Transactional
When you are in the process of ensuring that Spring's transaction support is enabled (see below@EnableTransactionManagement
), Spring Boot automatically enables transaction management when there is a data source. Therefore, in Boot scenarios, no additional configuration is required to be used.
@JsonFormat
Introduction: @JsonFormat
It is a serialization/deserialization formatting annotation provided by Jackson (). Can be used in fields, methods (
getter
/ setter
) or type, used to customize date-time, number, boolean and other properties inJSON ←→ JavaThe form, time zone and localization settings during conversion.
Functions and scenarios:
-
Date and time formatting:Will
Date
/LocalDateTime
etc. formatted to fixed strings (e.g.yyyy-MM-dd HH:mm:ss
) and specify a time zone to avoid time offset caused by inconsistent default time zones in front and back ends. -
Digital/Bolean Form Control: Can serialize boolean values into
0/1
, orInstant
、LocalDateTime
Convert to numeric timestamp (shape = NUMBER
)wait. -
In conjunction with Bean Validation: Cooperate simultaneously in DTO
@DateTimeFormat
/ Verify the annotation to keep the front and back end formats completely consistent. -
Priority: Field level
@JsonFormat
Will coverObjectMapper
Global date format configuration, suitable for scenarios where separate fields require special formats.
Example of usage:
@Data public class OrderDTO { private Long id; // 1. Specify date-time format + time zone @JsonFormat(shape = , pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createdAt; // 2. Output in seconds time stamp @JsonFormat(shape = ) private Instant eventTime; // 3. Change the boolean value to 0 / 1 @JsonFormat(shape = ) private Boolean paid; }
@Getter
Introduction: @Getter
It is a generator annotation provided by Lombok (). Automatically generates annotated classes or fields during the compilation period.public getterMethod, save handwritten boilerplate code.
Functions and scenarios:
- Simplify POJO/DTO writing: One annotation can generate read methods for all fields (or separate fields), keeping the class simple.
- Integrate with frameworks: Frameworks such as Spring/Jackson/Hibernate can directly use the method generated by Lombok when reading properties by getters.
Example of usage:
@Getter // Generate getter for all fieldspublic class UserVO { private Long id; @Getter() // The getter for this field is not generated private String password; // You can also add @Getter at the field level to generate only a single method}
rely: Development environment needs to be introduced
lombok
Depend on, and install the Lombok plug-in in the IDE or enable Annotation Processing.
@Setter
Introduction: @Setter
Also provided by Lombok (), automatically generated for classes or fieldspublic settermethod.
Functions and scenarios:
- Variable object assignment: Used when you need to modify the field value or frame reflection injection.
-
Granularity control: Can be passed
AccessLevel
Set method visibility (e.g.@Setter()
), or only use on specific fields to avoid exposing all writable interfaces.
Example of usage:
@Getter @Setter // Generate setters for all fieldspublic class ProductVO { private Long id; @Setter() // Only internal class can be modified private BigDecimal price; // Price's setter is private, and the other fields' setter is public}
@ToString
Introduction: @ToString
Also provided by Lombok (). Generate during compilation
toString()
Method, automatically splicing field names and values, supports including/excluding specific fields, hiding sensitive information, etc.
Functions and scenarios:
-
Debugging and logging: Quickly output object content without having to handwriting
toString()
。 -
Avoid sensitive field leaks: Available
@
Exclude fields, or set them on annotationcallSuper = true
Contains the parent class field. -
Chain annotation: Often with
@Getter/@Setter/@EqualsAndHashCode
Use it together to quickly generate complete data classes.
Example of usage:
@Getter @Setter @ToString(exclude = "password") // Exclude passwordpublic class AccountVO { private String username; @ private String password; // Or field level exclusion private LocalDateTime lastLogin; } /* Output example: AccountVO(username=admin, lastLogin=2025-05-10T20:30:00) */
Be sure to exclude sensitive information when outputting objects in production logs;
@ToString
supportexclude
Array or field level@
Fine control.
@EnableTransactionManagement
Introduction: @EnableTransactionManagement
Annotations are used to enable Spring pairsTransaction Notes(like@Transactional
) support. Provided by Spring (). Generally added to the configuration class.
Functions and scenarios:In non-Spring Boot scenarios, use@Transactional
This annotation is usually required to add this annotation to the Java configuration class or configure it in XML<tx:annotation-driven/>
to enable transaction AOP. It registers transaction management-related postprocessors to detect@Transactional
And generate a proxy at runtime.Provide modules: Spring Tx。
Example of usage:
@Configuration @EnableTransactionManagement public class TxConfig { @Bean public PlatformTransactionManager txManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); // Configure the transaction manager } }
The above example passed@EnableTransactionManagement
Annotation-driven transaction management is enabled and the data source transaction manager bean is explicitly declared. In Spring Boot, ifspring-boot-starter-jdbc
Or JPA, will be automatically configuredDataSourceTransactionManager
orJpaTransactionManager
, and transaction support is enabled by default, without manually adding this annotation (Boot will be applied automatically). But understanding the role of this annotation is still important when more granular control over transaction behavior is needed.
@Query
Introduction: @Query
Annotations provided by Spring Data JPA (), used to define custom ones on Repository methodsJPQL or native SQL query。
Functions and scenarios:Although Spring Data JPA can automatically generate queries by parsing method names, complex or special queries can be used@Query
Handwritten JPQL statements. You can also set itnativeQuery=true
Use native SQL. This annotation is useful when automatic generation fails to meet the needs, or when database-specific queries are used for performance.Provide modules: Spring Data JPA。
Example of usage:
public interface UserRepository extends JpaRepository<User, Long> { // Use JPQL query @Query("SELECT u FROM User u WHERE = ?1") User findByEmail(String email); // Query with native SQL @Query(value = "SELECT * FROM users u WHERE = :status LIMIT :limit", nativeQuery = true) List<User> findTopByStatus(@Param("status") int status, @Param("limit") int limit); }
In the above repository interface:
-
findByEmail
Methods use JPQL query to get users based on mailbox.?1
Indicates the first parameter. -
findTopByStatus
Method uses native SQL to query several users with specified status, and uses named parameters:status
and:limit
. Need to match@Param
Annotate the bound parameter value.
Spring Data JPA parses these annotations at runtime and generates corresponding implementation code execution queries.@Query
It can greatly improve the flexibility of query, but pay attention to the correctness of JPQL statements and the portability of native SQL.
8. Annotation of the section-oriented programming (AOP)
Spring AOP provides powerful tangent-oriented programming functions, which can define cross-cutting concerns through annotations, such as logging, performance monitoring, permission checking, etc. The main AOP notes include:
@Aspect
Introduction: @Aspect
Annotations are used to declare a class asFace-cut. Provided by AspectJ (Spring AOP uses AspectJ annotation style). Tagged as@Aspect
The class can define points and notifications inside to implement the AOP function. Need to be used with Spring AOP.
Functions and scenarios:The section class summarizes the cross-cutting logic, such as log sections, security sections, etc. A section class usually contains several notification methods (@Before, @After, etc.) and point-cut definitions (@Pointcut). Spring generates proxy objects according to the facet definition at runtime, weaving cross-cutting logic into the target object's method call.Provide modules: (Requires spring-boot-starter-aop or Spring AOP module dependencies).
Example of usage:
@Aspect @Component // The section itself also needs to be registered as a Beanpublic class LoggingAspect { // Point-cut definition: matches the public methods of all classes under the service package @Pointcut("execution(public * ..*(..))") public void serviceMethods() {} // Pre-notification: Execute before the method that satisfies the tangent point @Before("serviceMethods()") public void logBefore(JoinPoint joinPoint) { ("Entering: " + ()); } // Post-notification: It will be executed regardless of whether the method is normal or the exception is over @After("serviceMethods()") public void logAfter(JoinPoint joinPoint) { ("Exiting: " + ()); } }
A log facet class is defined aboveLoggingAspect
:
- use
@Aspect
Mark as facets, combined@Component
Make it a Spring Bean. -
serviceMethods()
Method Use@Pointcut
Define a point-cut, expression"execution(public * ..*(..))"
Indicates a matchAny public method of all classes under packages and subpackages is executed. The point-cutting method itself is not implemented and is only used as a mark.
-
logBefore
Method Use@Before("serviceMethods()")
Annotation means that the matching is being performedserviceMethods()
This notification is performed before any method of tangent point. - pass
JoinPoint
Parameters can obtain information about the called method.logAfter
Method Use@After("serviceMethods()")
, means that the target method is executed after the execution is completed (whether successful or not). Output method signature exit log.
For the above AOP to take effect, Spring support for AspectJ facets is required. Spring Boot Autoconfiguration has enabled AOP (if starter-aop is introduced, @AspectJ support will be enabled by default), and it may be necessary to add it to the configuration class in non-Boot environments.@EnableAspectJAutoProxy
Annotation to enable the proxy mechanism. If not enabled,@Aspect
The annotation will not take effect. Anyway,@Aspect
The annotated class defines the cross-cutting logic of AOP and is the key to implementing cross-cutting concerns such as logs, transactions, and permissions.
@Pointcut
Introduction: @Pointcut
Used to define aPoint-cut expression, reuse point tangents in naming. Provided by AspectJ annotation. Usually a method annotation signed with void and has no implementation, used to name the point tangent.
Functions and scenarios:The tangent point defines which joint points (Join Points) need to be weave into the surface logic. pass@Pointcut
Complex point-cut expressions can be abstracted to facilitate reference on multiple notifications and avoid repeated writing of expressions.Provide modules: AspectJ。
Example of usage:
@Aspect @Component public class SecurityAspect { // Point-cut: All methods containing @GetMapping annotations in the controller package @Pointcut("within(@ *) && @annotation()") public void allGetEndpoints() {} @Before("allGetEndpoints()") public void checkAuthentication() { // Execute permission verification logic if (!()) { throw new SecurityException("User not authenticated"); } } }
Here,SecurityAspect
Define a point cutallGetEndpoints()
,pass@Pointcut
The expression specified for annotation: Any annotated@RestController
In the class, the@GetMapping
The methods are all cut points. Then in@Before("allGetEndpoints()")
This point in the notification is referenced and permission check is performed. If the current user is not authenticated, an exception is thrown to prevent the method from executing.
The point-cut expression language is very rich, and can be matched and combined based on execution method signatures (execution), annotation (@annotation, within, etc.), this/target objects, etc. With appropriate tangent point definitions, you can flexibly select which points to apply cross-cutting logic.
@Before
Introduction: @Before
Define aPre-Notice(Advice), that is, the aspect method executed before the target method is executed. It is provided by AspectJ (). Need to be in
@Aspect
Used in a tangent class, the annotated value is a point tangent expression or named point tangent.
Functions and scenarios:Pre-notifications are usually used to perform some checks, logs, or preparations before a method call. For example, permission verification (see the above example), recording method start logs, setting up the environment before method execution (such as initializing ThreadLocal), etc. Execute before the target method, and does not affect the target method parameters and execution results, only additional operations are performed.
Example of usage:Refer to the foregoingLoggingAspect
andSecurityAspect
In-house@Before
usage. existLoggingAspect
middle:
@Before("serviceMethods()") public void logBefore(JoinPoint joinPoint) { ... }
This means that it is matchedserviceMethods()
Called before execution of each target method of the tangentlogBefore
method.JoinPoint
Parameters can obtain method signature, parameters and other information for log output.
@Before
Notifications cannot prevent the target method from being executed (unless an exception is thrown). If an exception is thrown in the notification, the target method will not be executed and the exception is thrown up. Therefore, the general pre-notification does not intentionally throw exceptions (except permission verification, if verification fails, execution is interrupted by exception).
@After
Introduction: @After
Define aPost-Notice, that is, it is executed in the target methodAfter the endThe executed facet method will be executed regardless of whether the target method returns normally or an exception is thrown (similar to finally block). Provided by AspectJ.
Functions and scenarios:Commonly used for cleaning resources, recording method end logs, etc. For example, record the execution time after the method is completed (needed to be combined with the start time), or ensure that some thread context data is cleared. Don't care about the result of the method, just leave the method and execute the notification.
Example of usage:refer toLoggingAspect
middle:
@After("serviceMethods()") public void logAfter(JoinPoint joinPoint) { ... }
in spite ofserviceMethods()
The matching method will be executed if it succeeds or returns exceptionallylogAfter
. You can use it to print the log of the method.
If you need to distinguish based on whether the method throws exceptions, you can use@AfterReturning
or@AfterThrowing
(See below for details).@After
It is usually used to place the final execution of operations, such as unlocking resources, and must be executed regardless of success or failure.
@AfterReturning
Introduction: @AfterReturning
Define aReturn to notification, execute after the target method returns successfully (exception is not thrown). The return value can be captured. Provided by AspectJ.
Functions and scenarios:When you need to get the return result of the target method for processing, you can use@AfterReturning
. For example, record the return value in the log, or perform subsequent actions based on the return value. If the target method throws an exception, this notification will not be executed. Annotation can specify the return property binding return value.
Example of usage:
@AfterReturning(pointcut = "execution(* (..))", returning = "result") public void logOrderResult(Object result) { ("Order placed result: " + result); }
This notification is forThe method executes, if it completes normally, the return value is bound to
result
Formal parameters and print the log. For example, result may be the order ID or confirmation object. likeplaceOrder
If an exception is thrown, the notification will not be executed.
@AfterThrowing
Introduction: @AfterThrowing
Define aException notification, execute after the target method throws a specified exception. Provided by AspectJ. Can catch exception objects.
Functions and scenarios:Used to uniformly handle or record exceptions thrown by the target method, such as recording error logs, sending alarms, etc. Can be specifiedthrowing
The property binds the exception to the parameter. Only execute when there is an uncaught exception, it will not be executed normally.
Example of usage:
@AfterThrowing(pointcut = "execution(* ..*.*(..))", throwing = "ex") public void logException(Exception ex) { ("Exception in method: " + ()); }
This aspect method will be executed when any uncaught exceptions in the application are thrown, printing exception information.ex
Parameters are exception objects thrown by the target method (you can specify specific exception type filtering, such asthrowing="ex" throwing=
)。
pass@AfterThrowing
Exception situations can be handled centrally, such as additional processing of specific exceptions (such as transaction compensation or resource recycling), or unified records.
@Around
Introduction: @Around
Define aSurround notification, it wraps the execution of the target method. Provided by AspectJ. Surround notifications are the most powerful, they can be processed before and after the method is executed, and can decide whether and how to execute the target method (throughProceedingJoinPoint
call).
Functions and scenarios:It can be used to calculate execution time, control method execution (such as implementing permission verification of custom annotations and determining whether to call the original method), modify the return value of the method, and even intercept exceptions.@Around
Notifications need to be called explicitlyproceed()
The target method will be executed. If it is not called, the target method will not be executed. This gives us the opportunity to insert logic before and after the call, and even change the execution flow.
Example of usage:
@Around("execution(* .*.*(..))") public Object measureExecutionTime(ProceedingJoinPoint pjp) throws Throwable { long start = (); Object result; try { result = (); // Execute the target method } finally { long end = (); (() + " executed in " + (end - start) + "ms"); } return result; }
This surround notification calculates execution time for all methods under the service package:
- Record the start time before calling the target method.
- pass
()
Execute the target method and save the return result. - After the method is executed, the time difference is calculated and printed.
- Return the return value of the target method to ensure that the calling process is progressing normally.
If the target method throws an exception,proceed()
An exception will be thrown to the outer layer (as in the above example, there is no catch, and the exception will continue to be thrown after finally execution). Exceptions can also be caught and processed in the surround notification, or even returned alternative results, thereby swallowing the exception (defaults to business needs).
@Around
Notifications can also implement functions such as custom annotation interception, such as checking whether there is annotation on the method, and implementing special logic when there is one, etc., with the highest flexibility.
@EnableAspectJAutoProxy
Introduction: @EnableAspectJAutoProxy
Is annotations provided by Spring (), used to enable annotation-based AOP support. It enables the automatic proxy mechanism for AspectJ annotations.
Functions and scenarios:In pure Spring configuration, you need to add this annotation to the configuration class to make the aforementioned@Aspect
The slicing takes effect (equivalent to the XML configuration<aop:aspectj-autoproxy/>
). Spring Boot has been enabled by default when introducing AOP startup dependencies, so it does not need to be explicitly added in most cases. But understanding this annotation helps to use when you need to adjust the AOP proxy options (e.g.proxyTargetClass=true
Force the use of CGLIB proxy).
Example of usage:
@Configuration @EnableAspectJAutoProxy(proxyTargetClass = true) public class AopConfig { // Slice the section class bean or scan the section class through @Component}
This will search in the container@Aspect
Annotated classes, automatically create proxy.proxyTargetClass=true
Force the use of class proxy instead of interface proxy. The default is false, that is, if there is an implementation interface, use JDK dynamic proxy. This can be set when you need to proxy classes that do not have interfaces or want to use CGLIB proxy uniformly.
In summary, Spring AOP's annotations allow us to implement cross-cutting logic in a declarative manner, separate logs, performance monitoring, security checks, etc. from business code, and improve modularity and maintainability.
9. Asynchronous and timed tasks annotations
Spring provides support for multi-threaded asynchronous tasks and timing scheduling, and these functions can be enabled by just annotation.
@Async
Introduction: @Async
Annotation is used to declare a method asasynchronousimplement. Provided by Spring (). The method that annotates this annotation will be executed asynchronously by Spring when called, rather than synchronously blocking the current thread. Usually required
@EnableAsync
Use together.
Functions and scenarios:When some operations do not need to be completed synchronously and can be executed in a background thread,@Async
Can simplify concurrent programming. For example, sending emails, SMS notifications, performing time-consuming calculations without blocking the main process, or calling multiple external services in parallel, etc. Spring will be based onTaskExecutor
(Default SimpleAsyncTaskExecutor) Scheduling asynchronous methods. Methods can returnvoid
orFuture
/CompletableFuture
In order to obtain the results.
Example of usage:
@Service public class NotificationService { @Async public void sendEmail(String to, String content) { // Simulate the time-consuming operation of sending emails try { (5000); ("Email sent to " + to); } catch (InterruptedException e) { ().interrupt(); } } }
@SpringBootApplication @EnableAsync // Enable asynchronous supportpublic class MyApp { ... }
existNotificationService
middle,sendEmail
Marked@Async
, so when it is called, Spring will take out a thread from the thread pool to execute the method asynchronously, and the original caller thread does not have to wait 5 seconds. Need to be added on the main application class or configuration class@EnableAsync
to activate asynchronous processing capability. When using the default configuration, Spring will be executed using a simple thread pool, or can be definedExecutor
Bean and add@Async("beanName")
to specify a specific thread pool.
Example of calling asynchronous method:
@RestController public class OrderController { @Autowired private NotificationService notificationService; @PostMapping("/order") public ResponseEntity<String> placeOrder(@RequestBody Order order) { (order); // Send notifications asynchronously ((), "Your order is placed."); return ("Order received"); } }
placeOrder
The method has been calledsendEmail
, because the latter is asynchronous,placeOrder
The response will be returned immediately after the message is triggered. The message is sent on another thread and does not affect the interface response time. Asynchronous call exceptions need to be handled specifically and can be usedAsyncUncaughtExceptionHandler
Or returnFuture
Listen on the caller. Anyway,@Async
It greatly facilitates asynchronous tasks.
@EnableAsync
Introduction: @EnableAsync
Is annotations provided by Spring (), used to enable pair
@Async
Processing of annotations. Added on the configuration class or main startup class to activate the ability to execute Spring asynchronous methods.
Functions and scenarios:Similar to@EnableAspectJAutoProxy
As for AOP, it also needs to be explicitly enabled for asynchronous purposes. Spring Boot automatic configuration usually does not actively turn on asynchronously, so developers need to add this annotation.Provide modules:Spring Context scheduling task support.
Example of usage:See above,@EnableAsync
Put@SpringBootApplication
It is OK on a class or on a separate configuration class.
When enabled, the Spring container will search for the app to be marked@Async
Bean methods and call thread pools to execute them through proxy mode. The default executor can be defined byTaskExecutor
Bean to cover. like:
@Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); (5); (10); (); return executor; }
After defining the executor named "taskExecutor", Spring@Async
It will be used automatically (because the default executor name is taskExecutor). Can also be in@Async
Specify a custom executor bean name in the annotated parameters.
@Scheduled
Introduction: @Scheduled
Annotations are used to mark a method asTiming tasks. Provided by Spring (). When to run this method can be configured by cron expressions or fixed intervals. Need to cooperate
@EnableScheduling
Turn on scheduling support.
Functions and scenarios:When a certain piece of code needs to be executed periodically, such as checking inventory every once in a while, generating reports every night, etc., you can use@Scheduled
Annotation without the need to rely on external scheduling frameworks. Spring containers call these methods in the background thread as specified schedule. Supports multiple scheduling configurations:
-
cron
Expression: Define complex time plans through Cron. - Fixed rate
fixedRate
:One time abovestartTime is the reference, and the interval is fixed milliseconds. - Fixed delay
fixedDelay
:One time aboveFinishTime is the basis, and the delay is fixed milliseconds. - Optional attributes such as
initialDelay
Set to set the startup delay.
Example of usage:
@Component public class ReportTask { @Scheduled(cron = "0 0 2 * * ?") public void generateDailyReport() { // Generate reports at 2 a.m. every day ("Generating daily report at " + ()); // ... Report generation logic } @Scheduled(fixedRate = 60000) public void checkSystemHealth() { // Check system health every 60 seconds ("Health check at " + ()); // ... Health Check Logic } }
here,ReportTask
In class:
-
generateDailyReport()
usecron="0 0 2 * * ?"
, means execution at 2:00 every day (Cron expression: "seconds, time, day, month, week", "?" means not specifying the weekday). This method will be called as scheduled on a scheduled basis on a scheduled basis by the scheduled thread. -
checkSystemHealth()
usefixedRate=60000
It means that it is executed every 60 seconds, and it is triggered at a fixed frequency no matter how long it lasts. If the last time has not been executed, the new cycle will not be executed concurrently by default (the scheduler will wait), but it can be configuredScheduler
Implement concurrency.
In order to make@Scheduled
Effective, need to be added on the configuration class@EnableScheduling
(see below). Spring Boot applications usually also need to add this annotation manually. The timing task execution is driven by Spring's TaskScheduler (default SingleThreadScheduler). You may need to note that the task should not block for a long time, otherwise it will affect subsequent task scheduling. Customizable thread pool TaskScheduler to improve concurrency.
@EnableScheduling
Introduction: @EnableScheduling
Annotation is used to enable Spring's support for timing task scheduling (). Added on the configuration class or main class.
Functions and scenarios:Without this annotation,@Scheduled
The annotation will not be recognized and processed. When enabled, the Spring container starts a scheduling thread pool and calls the marked method regularly.Provide modules:Spring Context timing task support.
Example of usage:
@SpringBootApplication @EnableScheduling public class Application { ... }
Will@EnableScheduling
Put it on the startup class to activate the scheduling mechanism. Then all@Scheduled
The annotation methods will be executed according to the configured plan. Spring Boot does not automatically enable timing task support, because some applications may not require scheduling functions, so they must be explicitly declared.
If you need a custom scheduler, you can define itScheduler
Bean orTaskScheduler
Bean. By default, all timing tasks are executed with a single thread. If multiple tasks need to be parallel, it is recommended to provide it.ThreadPoolTaskScheduler
Bean。
pass@Async
and@Scheduled
This set of annotations, Spring makes concurrent programming and task scheduling very easy, no longer need to explicitly create threads or use external scheduling platforms, and these logic can be completed inside the application.
10. Cache annotation
Spring provides a convenient caching mechanism, which can realize method-level caching through annotations, store method call results, and avoid repeated calculations or database queries.
@EnableCaching
Introduction: @EnableCaching
Annotations are used to enable Spring pairsCache annotationSupport (). Usually added to the configuration class or main class to activate cache management capabilities.
Functions and scenarios:After opening, Spring will automatically configure a cache manager (can be based on memory, EhCache, Redis, etc., depending on the dependency configuration) and scan the cache annotations in the application (such as@Cacheable
etc.), use AOP proxy to implement cache logic at runtime.Provide modules: Spring Cache。
Example of usage:
@SpringBootApplication @EnableCaching public class Application { ... }
In this way, Spring Boot will automatically select cache implementation based on the cache library in the classpath (if spring-boot-starter-cache is simply implemented using ConcurrentMapCache by default; if spring-boot-starter-redis is introduced, RedisCacheManager is used, etc.). Make sure it is called before using the cache annotation@EnableCaching
, otherwise the cache annotation will not take effect.
@Cacheable
Introduction: @Cacheable
Used to mark the method and cache its return result. Provided by Spring (). When calling this method again, if the passed parameters are the same and there is a result in the cache, the cache will be returned directly without executing the method.
Functions and scenarios:Typically used to read operation caches, such as querying data from the database and cache them. The next time you query the same parameters, you can directly return the cache value to improve performance.@Cacheable
You need to specify the cache name (cacheName) and the cache key (key), which can be a SpEL expression. The default key is automatically generated based on all parameters (the parameters can be hashed).
Provide modules: Spring Cache。
Example of usage:
@Service public class ProductService { @Cacheable(value = "products", key = "#id") public Product getProductById(Long id) { // Suppose there are complex calculations or slow database queries here ("Loading product " + id + " from DB..."); return (id).orElse(null); } }
Configuration@Cacheable(value="products", key="#id")
:
-
value
The name of the specified cache is "products" (similar to the category, which can correspond to different cache storage). -
key="#id"
Indicates usage parametersid
As a cache key.
First callgetProductById(1L)
When the database is printed, "Loading product 1 from DB..." will be queried, and the result will be cached in a cache named "products", with the key1
. The second callgetProductById(1L)
, Spring detects that the same key has a value in the cache, and returns to the cache directly, and does not execute the method body, so that the log will not be printed again.
@Cacheable
There are some properties:
-
condition
: Only cache or check cache when the conditions are met, such ascondition="#id > 10"
. -
unless
: After the method is executed, if the condition is met,No cacheThe result is,unless="#result == null"
. -
sync
: Whether to synchronize in concurrent scenarios, only one thread calculates the cache, and others wait.
@CachePut
Introduction: @CachePut
Annotations are used to return a method to a valuePut it directly into the cache, but with@Cacheable
The difference is that itAlways execute method, will not be skipped. It is usually used to update cached data. Provided by Spring.
Functions and scenarios:After performing the modification operation, you want the cache to be updated synchronously with the database, you can use@CachePut
Mark the modification method so that the results are written to the cache in time. In this way, you can get the latest value after reading the cache.Provide modules: Spring Cache。
Example of usage:
@CachePut(value = "products", key = "#") public Product updateProduct(Product product) { ("Updating product " + ()); return (product); }
Each callupdateProduct
, the save operation will be performed and the updatedProduct
。@CachePut
Annotation ensures that this returnsProduct
The object will use itid
As a key, save the "products" cache (overwrite the old value). Therefore, even if it was passed@Cacheable
Caches oldProduct
Data will also be updated here to make it consistent with the database. It is worth noting that@CachePut
It will not affect the execution of the method (the method will always be executed), it just writes the result to cache after returning.
@CacheEvict
Introduction: @CacheEvict
Annotations are used forRemove cache. Tagged on a method, the specified key or the entire cache can be cleared before or after the method is executed. Provided by Spring.
Functions and scenarios:When the data is deleted or changed and the cache is no longer valid, the cache needs to be cleared. For example, after deleting a record, you need to delete the corresponding cache; after batch updates, you can choose to clear the entire cache.@CacheEvict
Supports specificationkey
Or setallEntries=true
Clear the entire named cache.Provide modules: Spring Cache。
Example of usage:
@CacheEvict(value = "products", key = "#id") public void deleteProduct(Long id) { ("Deleting product " + id); (id); }
CalldeleteProduct(5)
hour,@CacheEvict
This will invalidate the entry with the middle key of "products" of 5 (delete). By default, it clears the cache after the method is successfully executed. If you want to clear whether the method is successful or not, you can set itbeforeInvocation=true
, that will be cleared when the method enters (prevents the method from throwing exceptions and cache is not clear).allEntries=true
You can directly clear the entire cache space regardless of the key. For example:
@CacheEvict(value = "products", allEntries = true) public void refreshAllProducts() { ... }
All entries in the "products" cache are cleared.
pass@CacheEvict
and@CachePut
, we can maintain the consistency between cache and underlying data.
Note: Using cache annotations requires correct configurationCacheManager
and cache storage. Spring Boot uses a simple memory cache (ConcurrentMapCacheManager) by default for development testing. Redis, Ehcache and other implementations are often combined in production. Replacing the implementation usually requires no changes to annotations, just configure the CacheManager Bean.
11. Event listening annotation
Spring provides an in-app event publish-subscribe mechanism to support loosely coupled message communication. Annotations allow you to easily subscribe to events.
@EventListener
Introduction: @EventListener
Is annotation introduced by Spring 4.2+ () , used to identify any Spring Bean method asEvent Listener. When there is a matching event published (implementation
ApplicationEvent
or custom event object), the method will be called. Comparatively implementedApplicationListener
Interface, the annotation method is simpler.
Functions and scenarios:Within the application, different components can communicate decoupled by publishing events. For example, after registering a user, publish aUserRegisteredEvent
, other listeners listen to send welcome emails or statistical indicators. use@EventListener
, the method signature defines the event type it is interested in, and can also be done throughcondition
Attributes set filtering conditions (for example, only deal with events that meet the conditions in a certain field).Provide modules:Spring Context event mechanism.
Example of usage:
// Define event class (can inherit ApplicationEvent or normal class)public class UserRegisteredEvent /* extends ApplicationEvent */ { private final User user; public UserRegisteredEvent(User user) { = user; } public User getUser() { return user; } } // Components for Publishing Events@Service public class UserService { @Autowired private ApplicationEventPublisher eventPublisher; public void register(User user) { // ... Save user logic // Publish an event (new UserRegisteredEvent(user)); } } // Components that listen to events@Component public class WelcomeEmailListener { @EventListener public void handleUserRegistered(UserRegisteredEvent event) { User newUser = (); // Send a welcome email ("Sending welcome email to " + ()); // ... Actual email sending logic } }
Process description:
-
After the new user is registered successfully, the method is passed
ApplicationEventPublisher
Posted aUserRegisteredEvent
event. Spring Boot passes by defaultApplicationEventPublisher
Publish events to the application context. -
WelcomeEmailListener
is a normal component (@Component
scanning). Which methodhandleUserRegistered
Marked@EventListener
, and the parameters areUserRegisteredEvent
. This indicates that it subscribes to this type of event. When the event is published, Spring detects that there is a matching listening method, and calls the method and passes the event object in. - The monitoring method is run to complete the function of sending welcome emails.
In this way, the logic of sending emails and the user service logic are completely decoupled and only contacted through events. If you do not need to send emails in the future, just remove the listener without affecting the user registration process. In addition, it is easy to add other listeners, such as listeners that count the number of registered users, without modifying the UserService.
@EventListener
Also supportedcondition
Properties use SpEL expressions for event content filtering. For example:
@EventListener(condition = "#") public void handleVipUserRegistered(UserRegisteredEvent event) { ... }
Processed only if the user is a VIP. This fine-grained control further enhances the flexibility of the event mechanism.
It should be noted that the default event listener executes synchronously within the publishing thread. If you want to handle events asynchronously, you can combine@Async
Annotation, asynchronously execute the listening method (provided that it is enabled@EnableAsync
). Or use the Spring 5 providedApplicationEventMulticaster
Configure asynchronous mode.
ApplicationListener
Interface (alternative)
illustrate:exist@EventListener
Before the emergence of Spring ImplementationApplicationListener<E>
Interface to listen for events. Although this is not annotation, it is worth mentioning when used in conjunction with event annotations. Any Spring Bean has been implementedApplicationListener<MyEvent>
,whenMyEvent
When it was publishedonApplicationEvent
The method will be called. Recommended since Spring 4.2@EventListener
Instead, it is more concise.
Example of usage:
@Component public class StatsListener implements ApplicationListener<UserRegisteredEvent> { @Override public void onApplicationEvent(UserRegisteredEvent event) { // Statistics user registration (""); } }
This listener does not require annotation, Spring automatically registers based on generics. But compared with the annotation method, it requires an independent class implementation interface, which is not as good as@EventListener
It can be convenient directly using any method. Moreover, a class can only implement monitoring of one event. To listen to multiple events, you need to write multiple classes or use some if judgments, which is not as flexible as annotations. Therefore, more use is now available in development@EventListener
。
In summary, Spring's event model realizes decoupling and collaboration within the application through publishing and subscriptions.@EventListener
It greatly lowers the threshold for use, making monitoring events as convenient as writing ordinary methods. With asynchronous capabilities, it can also achieve a message queue-like effect, and is used in less critical asynchronous notifications and other scenarios.
12. Test related notes
Spring provides a series of annotations to simplify the configuration test context for easy writing tests, especially for components such as Spring MVC or JPA.
@SpringBootTest
Introduction: @SpringBootTest
It is annotation provided by the Spring Boot test framework (), used on the test class, means starting a complete Spring Boot application context for integration testing.
Functions and scenarios:The test class labeled this annotation starts the application at runtime via Spring Boot boot (unless a specific property is configured to partially boot) which means:
- All beans are scanned and created to load the full application context.
- Provides dependency injection support for beans so that test classes can be directly
@Autowired
Need beans for integration testing.
It is often used in scenarios where multiple levels of work together are required, such as verification of service layer and warehouse layer interaction, or the entire request process.
Example of usage:
@SpringBootTest class ApplicationTests { @Autowired private UserService userService; @Test void testUserRegistration() { User user = new User("alice"); (user); // Verify the registration results, such as checking the database or event release effect assertNotNull(()); } }
This test class uses@SpringBootTest
, then when the test runs, Spring Boot will start the application context and injectUserService
Bean, the business code can be called directly in the test method for verification.@SpringBootTest
You can also specify startup port, environment and other parameters, or throughproperties
Override configurations, such as:
@SpringBootTest(webEnvironment = .RANDOM_PORT)
Used to start the embedded server on a random port for web integration testing.
@WebMvcTest
Introduction: @WebMvcTest
is annotation used to test Spring MVC controllers (). It starts a streamlined Spring MVC environment that only contains web-related beans, such as @Controller, @RestController, etc., as well as MVC configuration without loading the entire application context.
Functions and scenarios:Mainly used forUnit Test Controller. Scan only by default@Controller
and@RestController
and other web-layer components, as well as necessary configurations (such as Jackson transformation, Validator). The service layer and repository layer beans will not be loaded unless specified through configuration. This way the test runs fast and focuses on MVC layer logic. Cooperate frequentlyMockMvc
(A tool provided by Spring to simulate MVC requests) Use to perform request/response tests for controllers.
Example of usage:
@WebMvcTest(controllers = ) class UserControllerTests { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; // Simulate UserService @Test void testGetUser() throws Exception { User user = new User(1L, "Bob"); // Define the user object when (1) is called given((1L)).willReturn(user); (get("/users/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Bob")); } }
This test class annotation@WebMvcTest()
:
- Spring Boot will only start with
UserController
Related MVC components, such asUserController
itself, MVC configuration, serialized components, etc. -
UserService
Because it is not a @Controller component, it will not be loaded automatically. Therefore, it is used@MockBean
Annotation (see later) creates a simulatedUserService
Bean, inject it intoUserController
avoids real service layer logic involved. - Test usage
MockMvc
Initiate a GET request to/users/1
, and assert that the return status 200 and the return name field in JSON is "Bob". Since we passedgiven((1L))
The simulation behavior is specified, so the controller will get the user object we constructed when calling userService.
In this way, you can test controller mapping, parameter analysis, return results, etc. without starting the entire application, or real database, etc.@WebMvcTest
Provides support for all aspects of Spring MVC (such as automatically configuring MockMvc).
@DataJpaTest
Introduction: @DataJpaTest
is annotation used to test the JPA persistence layer (). It starts a Spring application context that contains only JPA-related components, such as entity managers, Spring Data JPA repository, embedded databases, etc.
Functions and scenarios:Mainly used forUnit Testing Repository Layer. It will:
- Configure an embedded in-memory database (such as H2) for testing unless another DataSource is explicitly specified.
- scanning
@Entity
Entity and Spring Data Repository interface and register. - Non-persistent layer beans loaded such as web, security, etc. to speed up testing.
- By default, each test is wrapped with transactions and rolled back at the end to ensure test isolation.
Example of usage:
@DataJpaTest class UserRepositoryTests { @Autowired private UserRepository userRepository; @Test void testFindByEmail() { // Prepare test data User user = new User(); ("test@"); ("Test"); (user); // Execute query method User found = ("test@"); assertEquals("Test", ()); } }
here@DataJpaTest
An in-memory database will be automatically configured and the JPA environment is initialized.UserRepository
The interface (assuming inherited from JpaRepository) will be loaded as a bean. In the test, save a user first, and then call the repository custom methodfindByEmail
Verification results. Since the transaction rolls back at the end of the test, the inserted test data does not contaminate the next test or the actual database.
@DataJpaTest
Also possible with@MockBean
If necessary, simulate some non-JPA beans, but usually persistence layer testing does not. Integration testing can also be tested via properties specifying connections to real databases, but in most cases, using an in-memory database is sufficient to test Repository logic.
@MockBean
Introduction: @MockBean
Is annotations provided by Spring Boot Test () , used to add a bean mocked by Mockito in the Spring test context and replace the bean that was originally of that type in the container (if any). It is often used to simulate dependable bean behavior in web or service layer testing.
Functions and scenarios:When the target bean of the test has dependencies and we do not want to test the real logic of the dependency (may be complex or uncertain), we can use it@MockBean
To provide a mock object created by Mockito to the container. This is more convenient than using it manually and then injecting it manually, because Spring will automatically inject this simulated bean into where it is needed. Typical applications are@WebMvcTest
In the simulation service layer bean,@SpringBootTest
Simulate external system client beans, etc.
Example of usage:
@MockBean private WeatherService weatherService;
WillWeatherService
The interface is simulated as a bean injection container. If the application context has a bean of that type (such as a real implementation), it will be replaced by a mock object. This allows us to usegiven(())...
Wait for preset behavior. This annotation can be used on the fields of the test class (as above), or on parameters within the test method.
The specific usage is in the previous one@WebMvcTest
Examples have been shown. For example, in a service layer test:
@SpringBootTest class OrderServiceTests { @Autowired private OrderService orderService; @MockBean private PaymentClient paymentClient; // Simulate external payment service client @Test void testOrderPayment() { Order order = new Order(...); // Assuming that the call to external payment returns a successful result given((order)).willReturn(new PaymentResult(true)); boolean result = (order); assertTrue(result); // Verify internal behavior, such as order status update // ... } }
Here OrderService depends on PaymentClient, but we don't want to actually call external services, so we simulate it with @MockBean and stipulate that PaymentResult is returned successfully. This way, the fake PaymentClient is actually used when executing, but it can be tested whether the OrderService's own logic correctly handles the successful results.Notice: @MockBean
The underlying layer uses Mockito, so you need to make sure that Mockito-related dependencies are introduced.
Other test notes:
-
@SpringBootTest
and@WebMvcTest
,@DataJpaTest
It is provided by Spring Boot TestTest section annotations, and there are similar@WebFluxTest
(Test the WebFlux controller),@JdbcTest
(Test JDBC),@JsonTest
(Test JSON serialization) etc., use as needed. - JUnit's own annotation is as
@Test
,@BeforeEach
,@AfterEach
etc. are also used extensively in testing (as in the above example, @Test has been used). Although it does not fall into the category of Spring, it is also considered one of the commonly used annotations in development.
With these test annotations, developers can easily write isolated test cases. For example, only launching the web layer or persistence layer for unit testing will greatly improve the test execution speed and accuracy of positioning problems. Spring Boot is automatically configured to crop the context for tests to avoid loading irrelevant beans, allowing tests to maintain production-like behavior and run efficiently.
13. Safety related notes
The Spring Security framework provides annotations and configuration annotations for method-level security control, which facilitates the implementation of permission checks on controllers or service methods. In addition, there are configuration annotations to enable security.
@EnableWebSecurity
Introduction: @EnableWebSecurity
is annotation for enabling Spring Security Web Security Support (). Usually added to a configuration class that inherits WebSecurityConfigurerAdapter (before Spring Security 5.7), or to a configuration class that contains SecurityFilterChain Bean. It enables the filter chain for Spring Security.
Functions and scenarios:When using Spring Security, this annotation is required to load the web security configuration so that the application is managed by Spring Security.Provide modules: Spring Security Config。
Example of usage:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and().formLogin(); } }
The above classic usage was configured before Spring Security 5.7 by inheriting the WebSecurityConfigurerAdapter.@EnableWebSecurity
Note to enable the security function. Spring Boot Autoconfiguration also adds this annotation when introducing starter-security, so sometimes it does not need to be added manually; but this annotation is generally stated when we provide a custom security configuration class.Notice:Starting from Spring Security 5.7, the official recommendation is not to inherit classes but to declare SecurityFilterChain Bean cooperation@EnableWebSecurity
Used, but the annotation works the same.
@EnableGlobalMethodSecurity
(Obsolete) /@EnableMethodSecurity
Introduction: @EnableGlobalMethodSecurity
Support for enabling method-level security annotations (e.g.@PreAuthorize
, @Secured
). This is annotation used by older versions of Spring Security, located in. It has been replaced with the new one in Spring Security 6
@EnableMethodSecurity
(@EnableGlobalMethodSecurity
marked as deprecated).
Functions and scenarios:Added on the Security configuration class to enable pairs@PreAuthorize
, @PostAuthorize
, @Secured
, @RolesAllowed
Identification of annotations. Various annotations can be enabled through its properties, such asprePostEnabled=true
Support Pre/PostAuthorize,securedEnabled=true
Support @Secured,jsr250Enabled=true
Support @RolesAllowed etc.Provide modules: Spring Security Config。
Example of usage (old):
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { // ... }
This will start@PreAuthorize/@PostAuthorize
(because prePostEnabled=true) and@Secured
Annotation (because securedEnabled=true). In Security 6, the equivalent approach is:
@Configuration @EnableWebSecurity @EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityConfig { ... }
@EnableMethodSecurity
Pre/Post is enabled by default, so you don't need to explicitly prePostEnabled, secured and jsr250 need to be explicitly true.
all in all, in the current Spring Boot 3 / Security 6 environment, use@EnableMethodSecurity
replace@EnableGlobalMethodSecurity
To enable method security annotation support.
@PreAuthorize
Introduction: @PreAuthorize
Is a method-level permission annotation for Spring Security (). It can be used on a method or class to perform permission verification based on the given expression before the method is called. This annotation will take effect only after global method security is enabled (as above).
Functions and scenarios: @PreAuthorize
You can check whether the current authenticated user has a certain permission or role, or meet any conditions defined by the SpEL expression before allowing the method to be executed. Commonly used in service layer or control layer methods to protect sensitive operations. For example, only the ADMIN role can call the delete user method, or only the resource owner can access the resource, etc. It's better@Secured
More powerful because you can write complex logic using Spring EL.
Example of usage:
@Service public class AccountService { @PreAuthorize("hasRole('ADMIN')") public void deleteAccount(Long accountId) { // Only ADMIN role users can execute (accountId); } @PreAuthorize("# == or hasAuthority('SCOPE_profile')") public Profile getUserProfile(User user) { // Users themselves or those with profile permissions can view return (user); } }
-
deleteAccount
Method,@PreAuthorize("hasRole('ADMIN')")
Restriction only users with ROLE_ADMIN can call it, otherwise it will be rejected (thrown)AccessDeniedException
)。getUserProfile
In terms of method, expressions are used:# == or hasAuthority('SCOPE_profile')
。Represents the current login username. If the
equals the current username (i.e. query your own information), or the current subject has
SCOPE_profile
Permissions (such as OAuth2 scope) allow access. Otherwise refuse. You can see that PreAuthorize can refer to method parameters (through # parameter name) and security context information (authentication object) for complex judgments.
@PreAuthorize
Very flexible and supports calling custom permission evaluation methods, etc. But be aware that the more complex the permission expression, the harder it may be to maintain, and a balance between security and readability is required. Spring Security officially recommends that PreAuthorize is better than Secured because it has stronger expressive power.
@Secured
Introduction: @Secured
It is an easy method security annotation provided by earlier Spring Security (). It specifies a set of allowed roles, and the user who calls the method must have one of them. Need to be enabled in the global method security configuration
securedEnabled=true
Only effective.
Functions and scenarios:Suitable for simple role-based access control. If the system's authorization model is mainly based on roles, it can be used@Secured("ROLE_X")
to protect the method. Compared to PreAuthorize, it does not support complex expressions and can only specify a list of roles.Provide modules:Spring Security (required@EnableMethodSecurity(securedEnabled=true)
or the old corresponding configuration).
Example of usage:
@Secured("ROLE_ADMIN") public void createUser(User user) { ... } @Secured({"ROLE_USER", "ROLE_ADMIN"}) public Data getData() { ... }
-
createUser
The method requires that the caller must haveROLE_ADMIN
Role. -
getData
Methods allowROLE_USER
orROLE_ADMIN
Owner access (logic is the relationship of OR).
If the requirements are not met, Spring Security will also throw an access denial exception.@Secured
In fact, it is also intercepted through AOP, and@PreAuthorize
The implementation mechanism is similar, but because of its limited functions, Spring officially recommends using Pre/PostAuthorize.
It should be noted that@Secured
The string in the annotation needs to contain the complete role prefix (such as the default prefix is "ROLE_"). As above, you must write "ROLE_ADMIN" instead of "ADMIN", unless the prefix policy is modified through configuration.
@RolesAllowed
Introduction: @RolesAllowed
From JSR-250 (), function and
@Secured
Similarly, it is also a list of roles that specify the allowed access to methods. Spring Security supports it, requiredjsr250Enabled=true
. The difference between it and Secured is mainly different from the annotation source.
Functions and scenarios:Can be used as@Secured
Instead of , use standard annotations to declare role limitations. The effect of both is the same in Spring environment.Provide modules:JSR-250, Spring Security requires support.
Example of usage:
@RolesAllowed("ADMIN") public void updateSettings(Settings settings) { ... }
Here it is assumed that the role prefix has been configured to be without the "ROLE_" prefix or the SecurityConfigurer has been processed, otherwise Spring Security will directly match the GrantedAuthority "ADMIN" as the role name. Generally, Secured and RolesAllowed cannot be mixed with different prefixes, otherwise errors are prone to occur.
In summary, these annotations provided by Spring Security allow us to automatically verify before calling without manually checking permissions within the method, and only execute the conditions if they meet the conditions. Need to note:
- To enable corresponding support on the configuration class (using
@EnableMethodSecurity
Or old version@EnableGlobalMethodSecurity
)。 -
@PreAuthorize
/@PostAuthorize
The most powerful, but slightly more complex.@Secured
/@RolesAllowed
Simple and direct, but only based on character judgment. - This type of annotation only checks the context of Spring Security and does not work for method calls that are not protected by filter chains (for example, self-calling methods in the same class will not trigger annotation checks, or in a security-free environment). This is a common trap - so it is best not to call methods with security annotations directly internally, otherwise the facet inspection will be bypassed.
14. Other common annotations
In addition to the above categories, there are some commonly used but uncategorized annotations in Spring & Spring Boot, such as:
-
Parameter verification related:Spring's support for JSR 303 Bean Validation allows us to use on models such as
@NotNull
,@Size
,@Valid
etc. Which is used on the Controller method parameters@Valid
Can trigger verification and combine@ExceptionHandler
or@ControllerAdvice
Unified processing of verification results. -
JSON serialization control:picture
@JsonInclude
(From Jackson) You can annotate classes or properties to control JSON serialization including rules, e.g.@JsonInclude(.NON_NULL)
Indicates that null value fields are ignored. This is useful when returning REST data. -
Conditional assembly annotations:Spring Boot offers a range of
@ConditionalOn...
Annotations are used for automatic configuration (e.g.@ConditionalOnProperty
,@ConditionalOnClass
,@ConditionalOnMissingBean
etc. to assemble the beans conditionally. These are mainly used when developing Spring Boot automatic configuration modules and are rarely used directly at the application layer, but understanding them helps to understand Boot's assembly mechanism.
The annotations listed above cover the most commonly used parts in Spring core development. From application startup configuration, bean assembly, to web layer development, data persistence, AOP, asynchronous, caching, events, testing, and security, there are concise annotation support in all aspects. Mastering their usage can significantly improve development efficiency, reduce boilerplate code, and let us pay more attention to business logic implementation.
Summarize:Spring & Spring Boot Common annotations greatly facilitate development. They follow the concept of "convention is better than configuration" and can complete the previously tedious XML configuration or manual encoding work through simple annotation declarations. When using it, pay attention to enabling the switches of the corresponding functions (such as asynchronous, transactions, caches, etc.), and understand the mechanism behind the annotation (such as AOP proxy, runtime processing) to avoid getting stuck. Proficient in using the above annotations, it can cover most daily development scenarios and achieve elegant, efficient and maintainable Spring applications.
This is the end of this article about the commonly used annotations of Spring Boot. For more relevant Spring Boot, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!