一、springcloud获取项目中的配置属性
-
配置文件
ibank: name: 1 code: zhangsanfeng
-
书写配置类
package com.example.demo.Config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data//set get @Component //主要要类进行加载扫描 @ConfigurationProperties(prefix = "ibank") //指定配置文件的开始属性 ---下边属性名字与配置文件中名字一致 public class IBank { private String name; private String code; }
1、注入调用
@Service
public class TestServiceImpl implements ITestService {
@Autowired
private IBank iBank; //注意注入
@Override
public String getBankName() {
return iBank ==null ? "":iBank.getName();
}
}
2、 使用util类获取参数
只修改调用位置未util类
/**注意:类要加@Component 需要被扫描 ,需要初始化方法 加@Autowired 加载扫描
* @Auther: 张娟
* @Date: 2021/04/14/16:47
* @Description:
*/
@Component
public class IBankUtil {
@Autowired
private IBank ibank;
public static IBank iBank =null;
@Autowired
public void init(IBank ibank) {
IBankUtil .iBank = ibank;
}
}
二、mvc框架配置文件
-
配置文件
//properties文件 imgageUpload.path=/tmp/ //tts 文件 imgageUpload.path=${imgageUpload.path}
-
书写配置类
package com.zkbc.core.util;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
public class GlobalProperties {
private static Logger logger = Logger.getLogger(GlobalProperties.class);
private static Properties props;
static{
String filename = "tts.properties";
InputStream is=GlobalProperties.class.getResourceAsStream("/" + filename);
props = new Properties();
try {
props.load(is);
}
catch (Exception e) {
logger.error("Cann't access the " + filename,e);
}
}
public static String getProperty(String name){
String val = props.getProperty(name.trim());
if(val == null){
return null;
}else{
//去除前后端空格
return val.trim();
}
}
public static String getProperty(String name, String defaultValue) {
String value = getProperty(name);
if(value == null){
value = defaultValue;
}
return value.trim();
}
public static List<Integer> getIntListItem(String item){
List<Integer> list = new ArrayList<Integer>();
String value = getProperty(item, "");
if(value.trim().isEmpty()){
return list;
}
String sepChar = ",";
if(value.indexOf(";")!=-1){
sepChar = ";";
}
String[] sa = value.split(sepChar);
for (int i = 0; i < sa.length; i++) {
String s = sa[i].trim();
if (s.isEmpty()) continue;
list.add(Integer.valueOf(s));
}
return list;
}
public static List<String> getListItem(String item){
List<String> list = new ArrayList<String>();
String value = getProperty(item, "");
if(value.trim().isEmpty()){
return list;
}
String sepChar = ",";
if(value.indexOf(";")!=-1){
sepChar = ";";
}
String[] sa = value.split(sepChar);
for (int i = 0; i < sa.length; i++) {
list.add(sa[i].trim());
}
return list;
}
public static void setProperty(String name ,String value){
props.setProperty(name, value);
}
}
- 调用
public class Config {
public final static String IMAGE_PATH= GlobalProperties.getProperty(" imgageUpload.path");
}