SpringBoot项目加载配置文件的6种方式

目录

​​​​​​1、通过@value注入

1.1、application.yml

1.2、配置类

2、通过@ConfigurationProperties注入

2.1、application.yml

2.1、配置类 

3、通过框架自带对象Environment实现属性动态注入

3.1、application.yml

3.2、配置类 

4、通过@PropertySource注解实现外部配置文件注入属性值

5、yml 外部配置文件动态注入

6、Java原生态方式注入属性值


​​​​​​1、通过@value注入

1.1、application.yml

minio:
  endpoint: http://127.0.0.1:9090
  accessKey: root
  secretKey: 123456
  bucketName: test

1.2、配置类

@Data
@Component
public class MinioClientConfig {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 注入minio 客户端
     *
     * @return
     */
    @Bean
    public MinioClient minioClient() {

        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

}


2、通过@ConfigurationProperties注入

2.1、application.yml

global:
  defaultPublicKey: MFwwDQYJKoZIhv
  defaultPrivateKey: MIIBUwIBADANBgkqhkiG9w0B
  #是否加密数据库密码 1-是
  globalIsDbDecrypt: 1
  #是否加密数据库密码 1-是 [如果没有密码,这里的配置无用]
  globalIsRedisDecrypt: 1
  DEFAULT_PUBLIC_KEY_STRING: MFwwDQYJKo
  #defaultPrivateKey: MIIEvQIBADANBgkqhkiG9
  DEFAULT_PRIVATE_KEY_STRING: MIIBUwIBADANBgkq

2.1、配置类 

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "global")
@Data
public class MarketProperties implements InitializingBean {

    private String globalIsDbDecrypt;
    private String globalIsRedisDecrypt;
    private String defaultPublicKey;
    private String defaultPrivateKey;
    private String DEFAULT_PUBLIC_KEY_STRING;
    private String DEFAULT_PRIVATE_KEY_STRING;
    private String MYSQL_FILE_PATH;
    private String QYWX_URL;


    public final static Map<String, String> map = new HashMap<>();


    @Override
    public void afterPropertiesSet() throws Exception {
        map.put("DEFAULT_PUBLIC_KEY_STRING", DEFAULT_PUBLIC_KEY_STRING);
        map.put("DEFAULT_PRIVATE_KEY_STRING", DEFAULT_PRIVATE_KEY_STRING);
        map.put("MYSQL_FILE_PATH", MYSQL_FILE_PATH);
        map.put("QYWX_URL", QYWX_URL);
    }

    public static String getConf(String key) {
        return map.get(key);
    }

    public static String getConf(String key, String def) {
        if (StringUtils.isBlank(map.get(key))) {
            return def;
        }
        return map.get(key);
    }

}


3、通过框架自带对象Environment实现属性动态注入

3.1、application.yml

mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.lhn.entity

3.2、配置类 


@Slf4j
//@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
    @Resource
    private Environment environment;

    @Bean
    @ConfigurationProperties(prefix = "mybatis-plus.configuration")
    public MybatisConfiguration globalConfiguration() {
        return new MybatisConfiguration();
    }

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource masterDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(masterDataSource);
        sqlSessionFactoryBean.setConfiguration(globalConfiguration());
        sqlSessionFactoryBean.setTypeAliasesPackage(environment.getProperty("mybatis-plus.type-aliases-package"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(environment.getProperty("mybatis-plus.mapper-locations")));

        return sqlSessionFactoryBean.getObject();
    }
}


4、通过@PropertySource注解实现外部配置文件注入属性值

4.1、通过@PropertySource注解实现导入外部配置文件。

4.2、配合@value注解实现属性注入或者@ConfigurationProperties注解实现批量注入。

4.3、该方式只能获取 .properties 的配置文件,不能获取 .yml 的配置文件。


5、yml 外部配置文件动态注入

5.1、自定义配置类,实例化PropertySourcesPlaceholderConfigurer类,使用该类进行属性值的注入。

5.2、实例化完PropertySourcesPlaceholderConfigurer类之后,就可以配合@value注解实现属性注入或者@ConfigurationProperties注解实现批量注入。

5.3、该方式只能获取.yml 的配置文件,不能获取 .properties 的配置文件。

6、Java原生态方式注入属性值

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以通过多方式加载配置文件,包括: 1. application.properties/application.yml文件:Spring Boot会自动加载classpath下的这两个文件,可以在其中定义应用程序的配置属性。 2. @PropertySource注解:可以通过该注解指定要加载配置文件,例如: @SpringBootApplication @PropertySource("classpath:myconfig.properties") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } 3. Environment接口:可以通过该接口获取配置属性的值,例如: @Autowired private Environment env; String value = env.getProperty("my.property"); 4. 自定义配置文件:可以通过实现org.springframework.boot.env.PropertySourceLoader接口来加载自定义的配置文件,例如: public class MyPropertySourceLoader implements PropertySourceLoader { @Override public String[] getFileExtensions() { return new String[] { "myconfig" }; } @Override public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { Properties props = new Properties(); props.load(resource.getInputStream()); return new PropertiesPropertySource(name, props); } } 然后在application.properties/application.yml中添加以下配置spring.profiles.active=myprofile spring.config.name=myconfig spring.config.location=classpath:/,classpath:/config/ 这样就可以在classpath:/或classpath:/config/目录下加载myconfig.myprofile文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值