zoukankan      html  css  js  c++  java
  • 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();  
        }  
    }
  • 相关阅读:
    SVN服务器搭建和使用
    oracle 存储过程
    PLSQL函数
    PL/SQL --> 游标
    PL SQL 游标学习
    PLSQL存储过程
    利用jqueryRotare实现抽奖转盘
    NSString 与NSMutableString的区别
    第一章 熟悉Objective -C 编写高质量iOS与OS X代码的52 个有效方法
    第8章 应用协议 图解TCP/IP 详解
  • 原文地址:https://www.cnblogs.com/zhaojinxin/p/7567500.html
Copyright © 2011-2022 走看看