java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot注入Bean

SpringBoot注入Bean的四种方式总结

作者:春来我不先开口,哪个虫儿敢作声?

这篇文章主要给大家总结SpringBoot注入Bean的四种方式,启动类注入Bean,启动类扫描@ComponentScan,启动类@EnableConfigurationProperties以及启动类@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);
    }
 
}

到此这篇关于SpringBoot注入Bean的四种方式总结的文章就介绍到这了,更多相关SpringBoot注入Bean内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文