一、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》