关于JAVA使用PropertySource读取配置文件及需要注意的地方

原文链接:https://www.cnblogs.com/warehouse/p/8681187.html

文章来自:https://www.cnblogs.com/warehouse/p/8681187.html的分享

网上记录的方法很多,这里只记录自己所使用的过的其中一种方法,不喜勿喷。

package com.demo.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
public class ConfigUtils {
    /**
     *  @PropertySource 读取配置文件必须返回一个  PropertySourcesPlaceholderConfigurer  的bean,否则会不能识别@Value("${demo}") 注解中的 ${demo}指向的value,
     *  而会注入${demo}的字符串,返回 PropertySourcesPlaceholderConfigurer 的方法,使用 @Bean 注解,表示返回的是个bean
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
         return new PropertySourcesPlaceholderConfigurer();
    }
    
    @Value("${demo}")
    private String demo;
    
    
    public String getDemo() {
        return demo;
    }

    public void setDemo(String demo) {
        this.demo= demo;
    }
    
    
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章