• SpringBoot-配置文件属性注入-3种方式


    配置文件:

    datasource.username = admin
    datasource.url = /hello/world

    方式一: @Value

    前提:

         <!-- JavaBean处理工具包 -->
         <dependency>
        <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
         </dependency>

    使用:

    @Component
    @Data
    public class PropertyBean {
        @Value("${datasource.url}")
        private String url;
        @Value("${datasource.username}")
        private String userName;
    }

    方式二:

    前提:

    <!-- 支持 @ConfigurationProperties 注解 -->  
         <dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-configuration-processor</artifactId>  
           <version>${spring-boot.version}</version>  
       </dependency>  

    使用: @ConfigurationProperties

    @Component
    @Configuration
    @EnableAutoConfiguration
    public class PropertyBeanUtil {
    
        @Bean
        @ConfigurationProperties(prefix = "datasource")
        public PropertyBean propertyBean() {
            return new PropertyBean();
        }
    
    }

     方式三:获得Environment 的对象

    @SpringBootApplication
    public class SpringBootDemo3Application {
    
        public static void main(String[] args) {
            final ApplicationContext ctx = SpringApplication.run(SpringBootDemo3Application.class, args);
            Environment environment = ctx.getEnvironment();
            System.out.println(environment.getProperty("datasource.username"));
        }
    }

    扩展:

     使用@PropertySource注解加载自定义的配置文件,但该注解无法加载yml配置文件。然后可以使用@Value注解获得文件中的参数值

    /**  
     * 加载properties配置文件,在方法中可以获取  
     * abc.properties文件不存在,验证ignoreResourceNotFound属性  
     * 加上encoding = "utf-8"属性防止中文乱码,不能为大写的"UTF-8"  
     */  
    @Configuration  
    @PropertySource(value = {"classpath:/config/propConfigs.properties","classpath:/config/db.properties"},  
            ignoreResourceNotFound = true,encoding = "utf-8")  
    public class PropConfig {  
      
        // PropertySourcesPlaceholderConfigurer这个bean,  
        // 这个bean主要用于解决@value中使用的${…}占位符。  
        // 假如你不使用${…}占位符的话,可以不使用这个bean。  
        @Bean  
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {  
            return new PropertySourcesPlaceholderConfigurer();  
        }  
    }
  • 相关阅读:
    处理emacs-org模式TODO的一个脚本
    MYSQL 数据类型
    Redis命令学习-Transaction(事务)
    成都青羊考场科目二考试分享
    地图入门_坐标系统
    microsoft SQL server,错误2
    搭建个人博客 方式2 使用jekyll
    WIN10 10招
    java正則表達式总结
    图解hdu5301Buildings
  • 原文地址:https://www.cnblogs.com/zhaojinxin/p/7567500.html
Copyright © 2020-2023  润新知