takeaway
Spring Boot project development has gradually become the mainstream framework in the Java application development field. It not only makes it easy to create production-grade Spring applications, but also can easily integrate with the current popular microservices framework SpringCloud through some annotations configuration.
The core reason why Spring Boot makes application creation and integration with other frameworks so easy is that it greatly simplifies project configuration and maximizes the “convention over configuration” principle. However, based on Spring Boot, although greatly facilitated development, it is also easy to make people “confused”, especially various annotations are easy to make people “know what it is and don’t know why”. **
Therefore, to use Spring Boot well, you must have a comprehensive and clear understanding of the annotations it provides. On the one hand, it can improve the development efficiency based on Spring Boot. On the other hand, it is also a necessary knowledge point to master when asked about the framework principle in the interview. In the next section, let’s explore some common Spring Boot annotations.
Spring related six annotations
Some of the Spring Boot annotations also need to be used with Spring annotations, so here’s a look at the six Spring infrastructure annotations that work most closely with Spring Boot annotations in your project. Such as 👇
1. @ the Configuration
From Spring3.0, @configuration is used to define Configuration classes that can replace XML Configuration files, annotated classes that contain one or more methods annotated by @bean, These methods will be AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext scanned, and used to construct the bean definition, initialize the Spring container.
@Configuration
public class TaskAutoConfiguration {
@Bean
@Profile("biz-electrfence-controller")
public BizElectrfenceControllerJob bizElectrfenceControllerJob() {
return new BizElectrfenceControllerJob();
}
@Bean
@Profile("biz-consume-1-datasync")
public BizBikeElectrFenceTradeSyncJob bizBikeElectrFenceTradeSyncJob() {
returnnew BizBikeElectrFenceTradeSyncJob(); }}Copy the code
2, @ ComponentScan
Those of you who have done web development have used the @Controller, @Service, and @repository annotations. If you look at the source code, there is a common annotation @Component, Yes, the @ComponentScan annotation will by default assemble classes that identify the @Controller, @Service, @Repository, and @Component annotations into the Spring container.
@ComponentScan(value = "com.abacus.check.api") public class CheckApiApplication { public static void main(String[] args) { SpringApplication.run(CheckApiApplication.class, args); }}Copy the code
The @SpringBootApplication annotation also includes the @ComponentScan annotation, so we can also configure the @SpringBootApplication annotation with the scanBasePackages attribute.
@SpringBootApplication(scanBasePackages = {"com.abacus.check.api"."com.abacus.check.service"}) public class CheckApiApplication { public static void main(String[] args) { SpringApplication.run(CheckApiApplication.class, args); }}Copy the code
3, @ Conditional
@Conditional is a new annotation provided by Spring4, through which you can load different beans according to the conditions set in the code. Before setting Conditional annotations, you must implement the Condition interface of the loaded bean class. The load condition is then set on the class that implements the interface. Annotations in Spring Boot, such as @conditionalonProperty and @conditionalonbean, which start with @Conditional, are all integrated with @Conditional to achieve corresponding functions.
4, @ Import
Add the instance to the springIOC container by importing it. Classes that are not managed by the Spring container can be imported into the Spring container as needed.
/ / class defines public class Square {} public class Circular {} / / Import @ Import ({Square. Class, Circular. Class}) @ the Configuration to the public class MainConfig{}Copy the code
5, @ ImportResource
Similar to @import, except that @importResource imports configuration files.
@ImportResource("classpath:spring-redis.xml"Public class CheckApiApplication {public static void main(String[] args) { SpringApplication.run(CheckApiApplication.class, args); }}Copy the code
6, @ Component
@Component is a meta-annotation that means you can annotate other class annotations, such as @Controller@servicer@repository. Classes with this annotation are considered components and are instantiated when annotation-based configuration and classpath scanning are used. Other class-level annotations can also be considered a special type of component, such as ** @controller Controller (which injects services), @Service Service (which injects DAOs), and @Repository dao (which implements DAO access). @Component is a generic name for a Component. This annotation can be used to annotate a Component when it is difficult to categorize, acting as an XML configuration.
Spring Boot core 20 notes
With a few basic Spring annotations that are closely related to Spring Boot, let’s take a look at the core annotations provided by Spring Boot.
1. @ SpringBootApplication
This annotation is the core annotation of Spring Boot. It is used on the main class of Spring Boot to indicate that this is a Spring Boot application. It is used to enable Spring Boot capabilities. This annotation is actually a combination of @Configuration, @enableAutoConfiguration, and @ComponentScan. Because these annotations are generally used together, SpringBoot provides a unified annotation @SpringBootApplication.
@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, DataSourceAutoConfiguration.class, ValidationAutoConfiguration.class, MybatisAutoConfiguration.class, MailSenderAutoConfiguration.class, }) public class API { public static void main(String[] args) { SpringApplication.run(API.class, args); }}Copy the code
2, @ EnableAutoConfiguration
Allows Spring Boot to automatically configure annotations that enable Spring Boot to configure Spring beans based on packages or classes in the current classpath.
For example, Mybatis JAR package is in the current classpath, MybatisAutoConfiguration annotation can configure each Spring Bean of Mybatis according to relevant parameters.
@ EnableAutoConfiguration implementation AutoConfigurationImportSelector is introduced, the key to its core logic is selectImports method, logic is roughly as follows:
-
Load all possible auto-configuration classes from the meta-INF /spring.factories configuration file;
-
De-weigh and exclude classes carried by the exclude and excludeName attributes;
-
Filter to return auto-configuration classes that meet the condition (@Conditional);
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @ AutoConfigurationPackage / / Import AutoConfigurationImportSelector subclasses of @ Import ({EnableAutoConfigurationImportSelector. Class}) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY ="spring.boot.enableautoconfiguration"; Class<? >[] exclude() default {}; String[] excludeName() default {}; }Copy the code
3, @ SpringBootConfiguration
This annotation is a variation of the @Configuration annotation and is used to modify the Spring Boot Configuration or to facilitate subsequent Spring Boot extensions.
4, @ ConditionalOnBean
ConditionalOnBean(a.class) A Bean is instantiated only if the A object exists in the current context, that is, the current Bean can only be created if A.class exists in spring’s applicationContext.
@bean // If DefaultMQProducer is present in the current context, To create RocketMQProducerLifecycle this Bean @ ConditionalOnBean (DefaultMQProducer. Class) public RocketMQProducerLifecyclerocketMQLifecycle() {
return new RocketMQProducerLifecycle();
}
Copy the code
5, @ ConditionalOnMissingBean
Combining the @Conditional annotation, as opposed to the @conditionalonBean annotation, instantiates A Bean only if the A object does not exist in the current context.
@bean // Only if the RocketMQProducer object is missing from the current context, @conditionalonmissingBean (RocketmqProducer.class) public RocketMQProducermqProducer() {
return new RocketMQProducer();
}
Copy the code
6, @ ConditionalOnClass
Combined with the @Conditional annotation, you can create a Bean only if some class exists on the classpath.
@bean // When the HealthIndicator class exists in the classpath, ConditionalOnClass(healthindicator.class) public HealthIndicator rocketMQProducerHealthIndicator(Map<String, DefaultMQProducer> producers) {if (producers.size() == 1) {
returnnew RocketMQProducerHealthIndicator(producers.values().iterator().next()); }}Copy the code
7, @ ConditionalOnMissingClass
Combination @ Conditional annotations, and @ ConditionalOnMissingClass annotations on the contrary, when the classpath does not specify a Class to open configuration.
8, @ ConditionalOnWebApplication
Combined with the @Conditional annotation, the configuration is enabled only if the project type is WEB project. There are currently three types of projects :ANY(ANY Web project matches), Servlets (only the underlying server projects match), and REACTIVE (only response-based Web applications match).
9, @ ConditionalOnNotWebApplication
Combination @ Conditional annotations, and @ ConditionalOnWebApplication annotations on the contrary, the current project types not open WEB project configuration.
10, @ ConditionalOnProperty
Combined with the @Conditional annotation, configuration is enabled only when the specified attribute has the specified value. This is done with the name and havingValue properties, where name is used to read a property value from application.properties. If the value is null, false is returned. If the value is not empty, it is compared with the value specified by havingValue, and returns true if the value is the same; Otherwise return false. If false is returned, the configuration does not take effect. True takes effect.
@ Bean / / match attribute rocketmq. Producer. If enabled values fortrue
@ConditionalOnProperty(value = "rocketmq.producer.enabled", havingValue = "true", matchIfMissing = true)
public RocketMQProducer mqProducer() {
return new RocketMQProducer();
}
Copy the code
11, @ ConditionalOnExpression
Combine @Conditional annotations to enable configuration only when the SpEL expression is true.
@Configuration
@ConditionalOnExpression("${enabled:false}")
public class BigpipeConfiguration {
@Bean
public OrderMessageMonitor orderMessageMonitor(ConfigContext configContext) {
returnnew OrderMessageMonitor(configContext); }}Copy the code
12, @ ConditionalOnJava
Combined with the @Conditional annotation, configuration is turned on only when the Java JVM running is in the specified version range.
13, @ ConditionalOnResource
Combined with the @Conditional annotation, configuration is enabled only when specified resources are in the classpath.
@Bean
@ConditionalOnResource(resources="classpath:shiro.ini")
protected Realm iniClasspathRealm() {return new Realm();
}
Copy the code
14, @ ConditionalOnJndi
Combine the @Conditional annotation to enable configuration only when the specified JNDI exists.
15, @ ConditionalOnCloudPlatform
Combined with the @Conditional annotation, configuration is enabled only when the specified cloud platform is active.
16, @ ConditionalOnSingleCandidate
Combined with the @Conditional annotation, configuration is enabled only when the specified class has only one Bean in the container, or when there are more than one but it is preferred.
17, @ ConfigurationProperties
Spring Boot can use annotations to map custom properties files to entity beans, such as config.properties files.
@Data
@ConfigurationProperties("rocketmq.consumer")
public class RocketMQConsumerProperties extends RocketMQProperties {
private boolean enabled = true;
private String consumerGroup;
private MessageModel messageModel = MessageModel.CLUSTERING;
private ConsumeFromWhere consumeFromWhere = ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET;
private int consumeThreadMin = 20;
private int consumeThreadMax = 64;
private int consumeConcurrentlyMaxSpan = 2000;
private int pullThresholdForQueue = 1000;
private int pullInterval = 0;
private int consumeMessageBatchMaxSize = 1;
private int pullBatchSize = 32;
}
Copy the code
18, @ EnableConfigurationProperties
When @ EnableConfigurationProperties annotation is applied to your @ Configuration, any @ ConfigurationProperties annotated beans will automatically be Environment Configuration properties. This style of configuration is particularly suitable for use with the external YAML configuration of SpringApplication.
@Configuration
@EnableConfigurationProperties({
RocketMQProducerProperties.class,
RocketMQConsumerProperties.class,
})
@AutoConfigureOrder
public class RocketMQAutoConfiguration {
@Value("${spring.application.name}")
private String applicationName;
}
Copy the code
19, @ AutoConfigureAfter
When applied to an auto-configuration class, the auto-configuration class needs to be configured after another specified auto-configuration class is configured.
Such as Mybatis automatic configuration class, need after data source automatic configuration class.
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
}
Copy the code
20, @ AutoConfigureBefore
This is the opposite of the @AutoConfigureAfter annotation, which means that the autoconfiguration class needs to be configured before another specified autoconfiguration class.
21, @ AutoConfigureOrder
Spring Boot 1.3.0 has a new annotation, @AutoConfigureOrder, that determines the priority order in which configuration loads are carried.
@ AutoConfigureOrder (Ordered. HIGHEST_PRECEDENCE) / / automatic Configuration inside the highest priority @ Configuration @ ConditionalOnWebApplication / / web application only @ Import (BeanPostProcessorsRegistrar. Class) / / Import the built-in container setting public class EmbeddedServletContainerAutoConfiguration { @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class }) @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { // ... } @Configuration @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { // ... }}Copy the code
The last
Here I recommend an architecture learning circle. Senior architects will share some recorded video and BATJ interview questions: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, microservice architecture principle, JVM performance optimization, distributed architecture and other necessary knowledge system for architects. I can also get free learning resources, which I benefit a lot from now.
Note: author: invincibility code farmers Original: www.cnblogs.com/wudimanong/…