日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

java通过spring获取配置文件_springboot获取properties文件的配置内容(转载)

發(fā)布時(shí)間:2024/9/30 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java通过spring获取配置文件_springboot获取properties文件的配置内容(转载) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、使用@Value注解讀取

讀取properties配置文件時(shí),默認(rèn)讀取的是application.properties。

application.properties:

demo.name=Name

demo.age=18

Java代碼:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class GatewayController {

@Value("${demo.name}")

private String name;

@Value("${demo.age}")

private String age;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解讀取

" name=" + name +

" , age=" + age;

}

}

運(yùn)行結(jié)果:

這里,如果要把

@Value("${demo.name}")

private String name;

@Value("${demo.age}")

private String age;

部分放到一個(gè)單獨(dú)的類(lèi)A中進(jìn)行讀取,然后在類(lèi)B中調(diào)用,則要把類(lèi)A增加@Component注解,并在類(lèi)B中使用@Autowired自動(dòng)裝配類(lèi)A,代碼如下。

類(lèi)A:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class ConfigBeanValue {

@Value("${demo.name}")

public String name;

@Value("${demo.age}")

public String age;

}

類(lèi)B:

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解讀取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age;

}

}

運(yùn)行結(jié)果:

注意:如果@Value${}所包含的鍵名在application.properties配置文件中不存在的話,會(huì)拋出異常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed;

nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'demo.name' in value "${demo.name}"

2、使用Environment讀取

application.properties:

demo.sex=男

demo.address=山東

代碼

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.env.Environment;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@Autowired

private Environment environment;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解讀取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age +

"

get properties value by ''Environment'' :" +

//2、使用Environment讀取

" , sex=" + environment.getProperty("demo.sex") +

" , address=" + environment.getProperty("demo.address");

}

}

運(yùn)行結(jié)果:

這里,我們?cè)赼pplication.properties做如下配置:

server.tomcat.uri-encoding=UTF-8

spring.http.encoding.charset=UTF-8

spring.http.encoding.enabled=true

spring.http.encoding.force=true

spring.messages.encoding=UTF-8

重新運(yùn)行結(jié)果如下:

3、使用@ConfigurationProperties注解讀取

在實(shí)際項(xiàng)目中,當(dāng)項(xiàng)目需要注入的變量值很多時(shí),上述所述的兩種方法工作量會(huì)變得比較大,這時(shí)候我們通常使用基于類(lèi)型安全的配置方式,將properties屬性和一個(gè)Bean關(guān)聯(lián)在一起,即使用注解@ConfigurationProperties讀取配置文件數(shù)據(jù)。

在src\main\resources下新建config.properties配置文件:

demo.phone=10086

demo.wife=self

創(chuàng)建ConfigBeanProp并注入config.properties中的值:

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

@Component

@ConfigurationProperties(prefix = "demo")

@PropertySource(value = "config.properties")

public class ConfigBeanProp {

private String phone;

private String wife;

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getWife() {

return wife;

}

public void setWife(String wife) {

this.wife = wife;

}

}

@Component 表示將該類(lèi)標(biāo)識(shí)為Bean

@ConfigurationProperties(prefix = "demo")用于綁定屬性,其中prefix表示所綁定的屬性的前綴。

@PropertySource(value = "config.properties")表示配置文件路徑。

使用時(shí),先使用@Autowired自動(dòng)裝載ConfigBeanProp,然后再進(jìn)行取值,示例如下:

import cn.wbnull.springbootdemo.config.ConfigBeanProp;

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.env.Environment;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@Autowired

private Environment environment;

@Autowired

private ConfigBeanProp configBeanProp;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解讀取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age +

"

get properties value by ''Environment'' :" +

//2、使用Environment讀取

" sex=" + environment.getProperty("demo.sex") +

" , address=" + environment.getProperty("demo.address") +

"

get properties value by ''@ConfigurationProperties'' :" +

//3、使用@ConfigurationProperties注解讀取

" phone=" + configBeanProp.getPhone() +

" , wife=" + configBeanProp.getWife();

}

}

運(yùn)行結(jié)果:

4.使用PropertiesLoaderUtils

app-config.properties

#### 通過(guò)注冊(cè)監(jiān)聽(tīng)器(`Listeners`) + `PropertiesLoaderUtils`的方式

com.zyd.type=Springboot - Listeners

com.zyd.title=使用Listeners + PropertiesLoaderUtils獲取配置文件

com.zyd.name=zyd

com.zyd.address=Beijing

com.zyd.company=in

PropertiesListener.java 用來(lái)初始化加載配置文件

package com.zyd.property.listener;

import org.springframework.boot.context.event.ApplicationStartedEvent;

import org.springframework.context.ApplicationListener;

import com.zyd.property.config.PropertiesListenerConfig;

/**

* 配置文件監(jiān)聽(tīng)器,用來(lái)加載自定義配置文件

*

* @authoryadong.zhang* @date 2017年6月1日 下午3:38:25

* @version V1.0

* @since JDK : 1.7

*/

public class PropertiesListener implements ApplicationListener{

private String propertyFileName;

public PropertiesListener(String propertyFileName) {

this.propertyFileName = propertyFileName;

}

@Override

public void onApplicationEvent(ApplicationStartedEvent event) {

PropertiesListenerConfig.loadAllProperties(propertyFileName);

}

}

PropertiesListenerConfig.java 加載配置文件內(nèi)容

package com.zyd.property.config;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;

import org.springframework.beans.BeansException;

import org.springframework.core.io.support.PropertiesLoaderUtils;

/**

* 第四種方式:PropertiesLoaderUtils

*

* @authoryadong.zhang* @date 2017年6月1日 下午3:32:37

* @version V1.0

* @since JDK : 1.7

*/

public class PropertiesListenerConfig {

public static Map propertiesMap = new HashMap<>();

private static void processProperties(Properties props) throws BeansException {

propertiesMap = new HashMap();

for (Object key : props.keySet()) {

String keyStr = key.toString();

try {

// PropertiesLoaderUtils的默認(rèn)編碼是ISO-8859-1,在這里轉(zhuǎn)碼一下

propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "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 MapgetAllProperty() {

return propertiesMap;

}

}

Applaction.java 啟動(dòng)類(lèi)

package com.zyd.property;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Map;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.zyd.property.config.PropertiesListenerConfig;

import com.zyd.property.listener.PropertiesListener;

/**

* @authoryadong.zhang* @date 2017年6月1日 下午3:49:30

* @version V1.0

* @since JDK : 1.7

*/

@SpringBootApplication

@RestController

public class Applaction {

/**

*

* 第四種方式:通過(guò)注冊(cè)監(jiān)聽(tīng)器(`Listeners`) + `PropertiesLoaderUtils`的方式

*

* @author zyd

* @throws UnsupportedEncodingException

* @since JDK 1.7

*/

@RequestMapping("/listener")

public Maplistener() {

Map map = new HashMap();

map.putAll(PropertiesListenerConfig.getAllProperty());

return map;

}

public static void main(String[] args) throws Exception {

SpringApplication application = new SpringApplication(Applaction.class);

// 第四種方式:注冊(cè)監(jiān)聽(tīng)器

application.addListeners(new PropertiesListener("app-config.properties"));

application.run(args);

}

}

總結(jié)

以上是生活随笔為你收集整理的java通过spring获取配置文件_springboot获取properties文件的配置内容(转载)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。