SpringBoot注入Bean的几种方式
目录
统一测试类与config类
1. 启动类注入Bean
2.启动类扫描@ComponentScan
3.启动类@EnableConfigurationProperties
4.启动类@Import
统一测试类与config类
yml
student:
red: dou
config
@Configuration注解 与 @Component注解都可以。
@Data
@Configuration
@ConfigurationProperties(prefix = "student") // 文件上传 配置前缀file.oss
public class MinIOConfigProperties implements Serializable {
private String red;
}
@Data
@Component
@ConfigurationProperties(prefix = "student") // 文件上传 配置前缀file.oss
public class MinIOConfigProperties implements Serializable {
private String red;
}
test
@SpringBootTest
class SpringBootTest01ApplicationTests {
@Autowired
private MinIOConfigProperties minIOConfigProperties;
@Test
void contextLoads() {
// 获取accessKey值
String accessKey = minIOConfigProperties.getRed();
System.out.println(accessKey);
}
}
1. 启动类注入Bean
@SpringBootApplication
public class SpringBootTest01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTest01Application.class, args);
}
@Bean
public MinIOConfigProperties minIOConfigProperties() {
return new MinIOConfigProperties();
}
}
2.启动类扫描@ComponentScan
@ComponentScan(basePackages = "com.ma.config")
@SpringBootApplication
public class SpringBootTest01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTest01Application.class, args);
}
}
3.启动类@EnableConfigurationProperties
@SpringBootApplication
@EnableConfigurationProperties(MinIOConfigProperties.class)
public class SpringBootTest01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTest01Application.class, args);
}
}
4.启动类@Import
@SpringBootApplication
@Import(MinIOConfigProperties.class)
public class SpringBootTest01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTest01Application.class, args);
}
}