1. 程式人生 > >SpringBoot配置檔案亂碼,訪問不到配置檔案,訪問多個配置檔案的的處理

SpringBoot配置檔案亂碼,訪問不到配置檔案,訪問多個配置檔案的的處理

package com.bojia.fund.proconfig;

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

@Component
@PropertySource(value={"classpath:application.properties","classpath:message.properties"},encoding="UTF-8")//設定編碼格式
public class MessageProperty {
		
	@Value("${msg_nopay}")
	private String msg_nopay;
	

	public String getMsg_nopay() {
		return msg_nopay;
	}

	
}

檔案目錄結構為src/main/re/application.properties,

                         src/main/resources/message.properties.

我這裡有兩個配置檔案,如果要引用MessageProperty 這個類的話在server層或者controller層加上如下程式碼:

@Controller
public class TestController {
	@Autowired
	MessageProperty property;

	@RequestMapping(value = "/index.do",produces="text/plain;charset=UTF-8",method = RequestMethod.GET)	
	public String index() {
	    //你的程式碼
		return null;
	}

}

我這裡是controller,server層也是一樣,就可以使用了,注意:

1.要用到@value這個註解的話,不要new,否則取不到值,我這裡用的是@Autowired
    MessageProperty property;
還有application.properties在resources目錄下,如果出現掃描不到xxx.properties等自定義配置檔案的話可能是你的

@PropertySource(value={"classpath:application.properties","classpath:message.properties"},encoding="UTF-8")配置錯誤,注意不要寫成

@PropertySource(value={"classpath:resources/application.properties","classpath:resources/message.properties"},encoding="UTF-8"),否認你會啟動報錯的,因為SpringBoot會依次預設從 src/main/resources/等路徑下查詢檔案,你就不要多此一舉在前面加一個"resources/"了

2.如果出現配置檔案中文亂碼就在註解@PropertySource裡面加上encoding="UTF-8",可以解決配置檔案中文亂碼問題!

3.多個配置檔案的話@PropertySource要用value={"classpath:application.properties","classpath:message.properties"}來指定

[email protected]得註解在@Component,@Server,@Controller下都可以拿到值