pycharm 网站开发,多语言商城源码,做网站如何文字链接文字,网站开发实用技术第2版文档其实理解一个注解就行了#xff20;SpringBootApplication#xff0c;我们的启动类其实就加了这一个
但是这么答也不行#xff0c;因为面试官要的答案肯定不止这一个
我们打开SpringBootApplication的源码#xff0c;会发现上面加了一堆的注解 相对而言比较重要是下面三个…其实理解一个注解就行了SpringBootApplication我们的启动类其实就加了这一个
但是这么答也不行因为面试官要的答案肯定不止这一个
我们打开SpringBootApplication的源码会发现上面加了一堆的注解 相对而言比较重要是下面三个但是ComponentScan这个是SpringContext里本身带的并不是SpringBoot引入的这个注解的作用是
扫描含有特定注解的类ComponentScan能够扫描指定包及其子包中所有使用Component、Service、Repository、Controller等注解的类并将这些类实例化为Bean注册到Spring容器中。这意味着开发者可以在需要的地方通过自动装配如Autowired直接使用这些Bean而无需手动创建。
扫描含有Configuration的类除了扫描注解Bean外ComponentScan还能扫描含有Configuration的类并使其配置生效。这允许开发者将配置类也纳入Spring容器的管理范围。
我们再解释一下其他两个注解的作用
1SpringBootConfiguration注解
SpringBootConfiguration的代码如下
Target({ElementType.TYPE})
Retention(RetentionPolicy.RUNTIME)
Documented
Configuration
Indexed
public interface SpringBootConfiguration {AliasFor(annotation Configuration.class)boolean proxyBeanMethods() default true;
}
这个注解的其实主要的就是引入了一个Configuration的注解SpringBoot启动类加SpringBootConfiguration这个的作用基本上等同于加了个Configuration注解表示当前SpringBoot的启动类也是一个配置类
2EnableAutoConfiguration注解
主要的代码逻辑如下
Target(ElementType.TYPE)
Retention(RetentionPolicy.RUNTIME)
Documented
Inherited
AutoConfigurationPackage
Import(AutoConfigurationImportSelector.class)
public interface EnableAutoConfiguration {/*** Environment property that can be used to override when auto-configuration is* enabled.*/String ENABLED_OVERRIDE_PROPERTY spring.boot.enableautoconfiguration;/*** Exclude specific auto-configuration classes such that they will never be applied.* return the classes to exclude*/Class?[] exclude() default {};/*** Exclude specific auto-configuration class names such that they will never be* applied.* return the class names to exclude* since 1.3.0*/String[] excludeName() default {};}
我们重点看最后一个它使用Import注解导入了一个AutoConfigurationImportSelector.class
这个是SpringBoot实现自动配置的最重要的类它用来加载classpath下spring.factories中所定义的自动配置类将这些类自动加载为配置Bean
3ConditionalOnXXX系列注解
ConditionalOn开头的注解在Spring Boot中非常常见它们提供了一套丰富的条件化配置机制允许开发者根据特定的条件来控制配置类或Bean的创建。这些注解基于Conditional元注解实现通过内部定义的Condition接口来判断条件是否满足
主要有以下几种
1. ConditionalOnBean 作用当指定的Bean存在时条件成立将创建当前Bean或激活当前配置类。
2. ConditionalOnMissingBean 作用当指定的Bean不存在时条件成立将创建当前Bean或激活当前配置类。
3. ConditionalOnClass 作用当类路径上存在指定类时条件成立将激活当前配置类。
4. ConditionalOnMissingClass 作用当类路径上不存在指定类时条件成立将激活当前配置类。
5. ConditionalOnProperty 作用当指定的配置属性具有特定的值时条件成立将创建当前Bean或激活当前配置类。
6. ConditionalOnExpression 作用当指定的SpELSpring Expression Language表达式的结果为true时条件成立将创建当前Bean或激活当前配置类。
这个其实一共应该有14种其他的不太常用。