Java读取properties内容
test=ceshi
package com.zhengyj.util;
import java.io.IOException;
import java.util.Properties;
public class factory {
private static Properties properties;
static{
properties = new Properties();
try {
properties.load(factory.class.getClassLoader().getResourceAsStream("extend.properties"));
String val = properties.getProperty("test");
System.out.println(val);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.zhengyj.util
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties
public class PropertyUtils{
private static Properties properties;
private static void setProperty(){
properties = new Properties();
Classloader loder = PropertyUtils.class.getClassLoader();
try{
properties.load(new InputStreamReader(loder.getResourceAsStream("extend.properties"),"utf-8"));
}catch(IOException e){
e.printStackTrace();
}
}
public static String getPropertyValue(String key){
setProperty();
return PropertyUtils.getPropertyValue(key,"default").trim();
}
}
spring方式
package com;
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 test {
@Autowired
private Environment env;
@RequestMapping(value = "/tes")
public String tes(){
return "q: "+env.getProperty("demo.url");
}
}
package com;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:conf.properties")
public class util {
@Value("${test}")
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}