
Spring 零碎知识记录
1、SpringBoot 自动装配
1.1 普通Bean的扫描(非自动配置类)
Spring Boot中与启动类不同包的普通组件(如Controller、Service等)的扫描,并不需要依赖spring.factories文件。这类组件的扫描规则与自动配置类无关。可以使用如下方法扫描普通 Bean
- 使用
@ComponentScan注解:直接指定需要扫描的包路径。 - 使用
@SpringBootApplication的scanBasePackages属性:例如@SpringBootApplication(scanBasePackages = {"com.example"})
1.2 自动配置类的注册(spring.factories的作用)
旧版本(Spring Boot 2.7之前):
自动配置类通过在
META-INF/spring.factories文件中配置org.springframework.boot.autoconfigure.EnableAutoConfiguration键值来实现。org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.hmall.common.config.MyBatisConfig,\ com.hmall.common.config.MvcConfig,\ com.hmall.common.config.JsonConfig新版本(Spring Boot 2.7+):
Spring Boot 2.7:引入了
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件作为新方式,但仍兼容spring.factories。Spring Boot 3.0+:完全移除了对
spring.factories的支持,仅支持AutoConfiguration.imports文件。
1.3 新版本中的自动配置方法
在新版本中,若需注册自定义自动配置类,需按以下步骤操作:
创建文件:在
resources/META-INF/spring/目录下新建org.springframework.boot.autoconfigure.AutoConfiguration.imports。填写配置类:在文件中写入全限定类名,例如:
com.example.MyAutoConfiguration
2、@ConfigurationProperties
用于将配置文件中的属性绑定到 Java 类的字段上,使用方法如下:
① 配置文件对应的类
@Data
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private String description;
}注意:这个类加上了 @Component 注解,否则 Spring 容器里面没有这个 bean。
② application.yml 配置文件
myapp:
name: My Application
description: Hello world!③ 使用(就像普通的、需要注入的 Bean 一样使用):
@Service
@RequiredArgsConstructor
public class MyService {
private final MyAppProperties myAppProperties;
public void printProperties() {
System.out.println("Name: " + myAppProperties.getName());
System.out.println("Description: " + myAppProperties.getDescription());
}
}还有一种方式是使用 @EnableConfigurationProperties 注解:
// 在任意会被 Spring 扫描的类中启用需要的配置类
@Service
// 该注解的作用是使 MyConfigurationProperties 这个类上标注的
// @ConfigurationProperties 注解生效,并且会自动将这个类注入到 IOC 容器中
@EnableConfigurationProperties(MyConfigurationProperties.class)
