一、Springboot生产服务需要配置文件在项目jar包外面,所以需要重新创建一个目录。
二、Springboot的加载配置文件一共有4种方法。
1.第一种:
获取属性值
@Value("${imagesUrl.name}")
private String name;
目录存在项目目录/src/main/resources的application.properties配置文件
imagesUrl.name=http://127.0.0.1
2.第二种
获取属性值
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource(value={"file:${user.dir}/config/application.properties"})
//@PropertySource(value={"classpath:application.properties"})
//默认访问本地的resource路径的配置文件
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context=SpringApplication.run(DemoApplication.class, args);
String str1=context.getEnvironment().getProperty("aaa");
System.err.println("---------"+str1);
}
}
目录存在位置项目目录下的config路径下application.properties
aaa=你好
3.第三种
获取属性的值
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class Config {
@Autowired
private Environment env;
public void test(){
//获取字符串
System.out.println("String: " +env.getProperty("string.port"));
}
}
目录存在项目目录/src/main/resources的application.properties配置文件
string.port=80
4.第四种
获取值
// 加载YML格式自定义配置文件
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new
PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new FileSystemResource("config.yml"));//File引入
// yaml.setResources(new ClassPathResource("youryml.yml"));//class引入
configurer.setProperties(yaml.getObject());
return configurer;
}
@Value引入属性值注入Bean
@Component
@ConfigurationProperties(prefix = "prefix")
public class Config {
// 以下属性可以直接获取
private String name;
private List<Map<String, String>> list = new ArrayList<>();
@Value("${your.username}")
private String username;
}
目录存在项目目录/src/main/resources的application.yml配置文件
prefix:
name:
list:
name: tech
key: 123
source: beijing
name: skill
key: 987
source: shanghai
your:
username: test
注意:
因为我是用的是eclipse,所以 file:${user.dir} 在windows环境下会取到eclipse路径下,而在linxu服务器上则会取到你当前放置war包的weblogic的domain下,之后拼接你的路径即可。 当然如果权限足够的话,也可以用file:${user.home}来获取properties的值,windows的话是document/../..的路径,如果是linxu则是根目录下home的路径。 当然如果你要取包内的properties,用classpath:就可以解决了,是取classes下的路径。 这样修改之后就能完成(war包或者jar包)和配置文件的分离。
《参考:https://blog.csdn.net/luckyrocks/article/details/79248016》