Preface
In Spring application development, conditional bean registration is a key link in configuration flexibility.@Profile
and@Conditional
They are two common mechanisms provided by Spring. They can dynamically determine whether certain beans are loaded according to different conditions, thereby realizing environmental isolation, module selection, feature switches and other functions. This article will systematically explain the role, usage of these two annotations, the differences and synergy between them.
1. What is @Profile
Basic concepts
@Profile
Annotations are used to specify that a bean or configuration class is effective only in the specified Profile environment. It is often used to distinguish configurations of development, testing and production environments.
@Configuration @Profile("dev") public class DevDataSourceConfig { @Bean public DataSource dataSource() { return new HikariDataSource("jdbc:mysql://localhost/dev_db"); } }
Activation method
- :
: dev
- Startup parameters:
--=dev
- SpringApplicationBuilder:
.profiles("dev")
2. What is @Conditional
Basic concepts
@Conditional
Annotations provide more general conditional judgment capabilities. Its parameters are implementedCondition
The interface class, Spring will call the classmatches
The method determines whether to load the corresponding bean.
@Bean @Conditional() public ListService windowsListService() { return new WindowsListService(); }
Custom Condition Example
public class WindowsCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return ().getProperty("").contains("Windows"); } }
3. Comparison of the two
Dimension | @Profile | @Conditional |
---|---|---|
granularity | Environment-level configuration | Code level, attribute level, arbitrary conditions |
Simplicity | Simple and easy to use, agreement is greater than configuration | Flexible but requires manual implementationCondition interface |
Applicable scenarios | Multi-environment configuration isolation (dev/test/prod) | Control bean loading according to any runtime conditions, such as system variables, class existence, etc. |
Compositionality | Can cooperate@Configuration 、@Component use |
Can be combined with any Spring annotation |
The underlying principle | The essence is@Conditional()
|
Completely customizedCondition Implementation Class |
4. Practical examples
Profile+Conditional combined use
@Configuration @Profile("prod") public class CacheConfig { @Bean @Conditional() public CacheManager redisCacheManager() { return new RedisCacheManager(); } }
This configuration means that onlyprod
In the environment, and exists in the classpathRedisClient
Created when the class isredisCacheManager
Bean。
5. Advanced @Conditional derived annotation
Spring Boot provides multiple@Conditional
The derived annotation simplifies the conditional configuration of common scenarios:
@ConditionalOnProperty
Function: Decide whether to load a Bean based on whether a property exists and its value in the configuration file
@Bean @ConditionalOnProperty(name = "", havingValue = "true", matchIfMissing = false) public UserFeatureService featureService() { return new UserFeatureService(); }
@ConditionalOnMissingBean
Function: Register the current bean only when the specified bean does not exist, and is used to provide a default implementation.
@Bean @ConditionalOnMissingBean() public DataSource defaultDataSource() { return new HikariDataSource(); }
@ConditionalOnBean
Function: When a bean exists in the Spring context, the current bean is injected.
@Bean @ConditionalOnBean() public CacheManager redisCacheManager() { return new RedisCacheManager(); }
@ConditionalOnClass
Function: Bean is loaded when a certain class exists in the classpath, which is suitable for automatic assembly of components.
@Bean @ConditionalOnClass(name = "") public JsonConverter jsonConverter() { return new JacksonJsonConverter(); }
These annotations greatly simplify the conditional logic of automatic configuration and are the core support of Spring Boot automatic assembly mechanism.
6. Summary
annotation | effect | Suitable for scenes |
---|---|---|
@Profile | Activate Bean by environment (such as dev/prod) | Multi-environment isolation configuration |
@Conditional | Activate beans based on any conditions (such as operating system, classpath) | Modular configuration with flexible control and scalability |
In actual projects, the two can be used in combination to build a highly flexible and configurable application architecture, which is an important tool for Spring framework decoupling and module control.
It is recommended to use it in configuration classes@Profile
Do environmental isolation and use in specific beans@Conditional
Do condition control.
The above is the detailed content of the difference between Java annotation @Conditional and @Profile. For more information about Java annotation @Conditional and @Profile, please follow my other related articles!