Spring和Java獲取properties文件的幾種方式

前言

獲取properties文件的方式大致可以分爲spring獲取和java自身獲取兩種。接下來我會主要從這兩方面爲大家演示每種方式獲取的例子。

環境準備:

1.新建一個springboot項目

2.需要引入的pom依賴

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- 配置文件自動映射 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

Spring獲取properties

方式一:使用@Value註解

在application.properties文件中添加屬性

my.name=擎天柱
my.age=20

在TestController中使用

@RestController
public class TestController {

    @Value("${my.name}")
    private String name;
    @Value("${my.age}")
    private int age;
    
    @RequestMapping("/test")
    public String hello() {
        System.out.println("TestController的方法被調用了");
        return "welcome to the new age !";
    }

    @RequestMapping(value = "/test2")
    public String test2() {
        return "my name is " + name + ",my age is" + age;
    }
}

結果展示:

方式二:使用Environment

@RestController
public class TestController {

    @Autowired
    private Environment env;
    
    @RequestMapping("/test")
    public String hello() {
        System.out.println("TestController的方法被調用了");
        return "welcome to the new age !";
    }

   @RequestMapping(value = "/test3")
    public String test3() {
        return "my name is " + env.getProperty("my.name") + ",my age is" + env.getProperty("my.age");
    }
}

結果展示:

方式三:使用@ConfigurationProperties註解編寫對應的配置類

@Data
@Component
@ConfigurationProperties(prefix = "my")
public class PropertiesConfig {
    private String name;
    private int age;
}
@RestController
public class TestController {

    @Autowired
    private PropertiesConfig config;

    @RequestMapping("/test")
    public String hello() {
        System.out.println("TestController的方法被調用了");
        return "welcome to the new age !";
    }


    @RequestMapping(value = "/test4")
    public String test4() {
        return "my name is " + config.getName() + ",my age is" + config.getAge();
    }
}

結果展示:

方式四: 使用PropertiesLoaderUtils

1.新建PropertiesListener監聽器

public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
    private String propertyFileName;

    public PropertiesListener(String propertyFileName) {
        this.propertyFileName = propertyFileName;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        PropertiesListenerConfig.loadAllProperties(propertyFileName);
    }
}

2.創建PropertiesListenerConfig

public class PropertiesListenerConfig {
    public static Map propertiesMap = new HashMap();

    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap<String, String>(16);
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils的默認編碼是ISO-8859-1,在這裏轉碼一下(本地默認改爲了utf-8)
                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
            processProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

    public static Map<String, String> getAllProperty() {
        return propertiesMap;
    }
}

3.註冊監聽器

@SpringBootApplication
public class DemoApplication {
    
    public static void main(String[] args) {
        //SpringApplication.run(DemoApplication.class, args);
        SpringApplication application = new SpringApplication(DemoApplication.class);
        // 第四種方式:註冊監聽器
        application.addListeners(new PropertiesListener("application.properties"));
        application.run(args);
    }

4.測試

@RestController
public class TestController {

    @RequestMapping("/test")
    public String hello() {
        System.out.println("TestController的方法被調用了");
        return "welcome to the new age !";
    }


    @RequestMapping("/test5")
    public String test5() {
        Map<String, String> map = PropertiesListenerConfig.getAllProperty();
        return "my name is " + map.get("my.name") + ",my age is" + map.get("my.age");
    }
}

結果展示:

 

演示完Spring的四種方式,接下來我再演示java自身的方式,請繼續往下看:

Java獲取properties

方式一:利用java.util.Properties讀取屬性文件

public class MainTest {

    public static void main(String[] args) {
        
        Properties properties = new Properties();
        try {
            //加載配置文件
            properties.load(MainTest.class.getClassLoader().getResourceAsStream("application.properties"));
            //亂碼處理:(1)選中配置文件-->右鍵-->Properties-->text file encoding
            // (2)使用上述代碼會出現亂碼情況時,修改爲在load配置文件時指定編碼格式爲UTF-8
            // properties.load(new InputStreamReader(MainTest.class.getClassLoader().getResourceAsStream("application.properties"), "UTF-8"));
            //遍歷配置文件中key和value
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }
            //根據key獲取value值
            System.out.println("myName=" + properties.getProperty("my.name"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

結果展示:

my.name:擎天柱
my.age:20
myName=擎天柱

方式二:外部文件處理


public class MainTest {

    public static void main(String[] args) {
        //外部文件處理
        Properties properties = new Properties();
        try {
            File file = new File("E:\\data\\application2.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            properties.load(new InputStreamReader(fileInputStream, "UTF-8"));
            System.out.println("application2--->myName=" + properties.getProperty("my.name"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

結果展示:

application2--->myName=擎天柱

 

總結:

以上就是常用的幾種獲取配置文件的方式,其中PropertiesLoaderUtils.loadAllProperties(propertyFileName)底層源碼也是利用了java的獲取方式,有興趣的同學可以看一下這個方法的底層源碼,這裏就不再贅述了。

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