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();  
    }  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM