dotnet core vs java_Java Spring Boot VS .NetCore (七) 配置文件

Spring Boot 配置文件

主要说下 properties & yml

下面来看下

application.properties的文件格式

Spring.datasource.url=jdbc:mysql://192.168.0.233:3306/test1?useSSL=false

Spring.datasource.username=uoso

Spring.datasource.password=uosotech_123

Spring.datasource.driver-class-name=com.mysql.jdbc.Driver

yml配置格式

spring1:

url1: dbc:mysql://192.168.0.102:3306/test1?useSSL=false

那么在代码中我们怎么来使用这些配置文件呢?

这里要介绍的就是注解 @Component  、 @Value 的使用了

默认只要编写名称为application.*.yml 都是能够被直接使用的,只需要把 配置文件映射到类的属性里面,代码如下

@Componentpublic classPropertiesConfig {

@Value("${Spring.datasource.url}")privateString database;publicString getDatabase() {returndatabase;

}public voidsetDatabase(String database) {this.database =database;

}

}

如果世界使用的application.yml 能够自动被填充的配置资源里面,写法给上面样就能拿到配置

我这里自定义一个yml 如:test.yml

这里需要添加依赖

org.springframework.boot

spring-boot-configuration-processor

true

重新构建后,我新建一个class ,这里需要说明的就是 @ProtertySource  指定yml的路径 需要注意是的 classpath 这个指向的地址,是打包后的目录,调试的时候肯定找不到对应路径目录的文件需要自己配置下,否则就放在下图的目录结构

75a11b169de9b6f832ce6a5b0b700e43.png

@Component

@PropertySource(value= "classpath:/test.yml")

@ConfigurationProperties(prefix= "spring1")public classYMLConfig {publicString getUrl1() {returnurl1;

}public voidsetUrl1(String url1) {this.url1 =url1;

}

@Value("${url1}")private String url1;

使用通过注解 @Autowired \ @Resource 都可以

//测试yml配置

@AutowiredprivateYMLConfig ymlConfig;

@Testpublic voidtestYmlConfig()

{

System.out.print(ymlConfig.getUrl1());

}

a4b351b8ebbe760481692ba94a271509.png

ab6829319378f1c1de179b2e1244b852.png

得到了我们想要的结果,下面在来说下.NetCore中的配置使用情况

.NetCore 配置文件

.NetCore提供了json 、xml 的方式来实现配置,这里我以json 来举个例子看下使用方式

默认也有一个appsettings.json 的文件,在不使用自定义配置的情况下,系统会加载这个配置文件 ,那么如果要把配置文件映射到class里面需要怎么处理呢?

下来创建一个配置类

public classAuthorityConfig

{public string Authority { get; set; }public bool RequireHttpsMetadata { get; set; }

}

在appsetting里面我们根据目录结构添加即可

"AuthorityConfig": {"Authority": "http://localhost:20001","RequireHttpsMetadata": false}

那么怎么把这两个Bind起来呢? 前面可以看到Java是通过@Value注解

.NetCore则是通过 在Startup 启动类中添加服务 里面有 IConfiguration 接口,根据这个接口来操作即可

services.AddOptions();

services.Configure(Configuration.GetSection("AuthorityConfig"));

根据节点位置配置关联的类,需要使用的时候通过构造函数注入即可

如果需要添加自定义的配置,我们使用启动类的构建来创建相关路径下的相关文件绑定到配置中Configuration 最后通过 Configuration 来绑定 Class之间的关系

publicStartup(IConfiguration configuration, IHostingEnvironment env)

{var configurationbuilder = newConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)

.AddXmlFile($"appsettings.xml", optional: true, reloadOnChange: true)

.AddEnvironmentVariables();

Configuration=configurationbuilder.Build();//Configuration = configuration;

}

总结

其实 Spring Boot中也有其他的方式加载自定义的文件  ,这里的 ConfugurationBuilder 跟 Spring Boot中的  PropertySourcesPlaceholderConfigurer 类似,Java还提供了2中创建方式

1、YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

2、YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

MutablePropertySources sources = new MutablePropertySources();

可以看到第二种里面多了MutablePropertySources,英文上就是加载多个资源文件的,事实就是这个意思,加载多个资源文件,而第一种没抛出异常

下面来解析下第一种:看源码

public class YamlPropertiesFactoryBean extends YamlProcessor implements FactoryBean, InitializingBean {private boolean singleton = true;

@NullableprivateProperties properties;publicYamlPropertiesFactoryBean() {

}public void setSingleton(booleansingleton) {this.singleton =singleton;

}public booleanisSingleton() {return this.singleton;

}public voidafterPropertiesSet() {if (this.isSingleton()) {this.properties = this.createProperties();

}

}

没有异常,而且是单例

看下第二种的源码,抛出了IO异常,在找不到文件目录文件的情况下会抛出异常

public class YamlPropertySourceLoader implementsPropertySourceLoader {publicYamlPropertySourceLoader() {

}publicString[] getFileExtensions() {return new String[]{"yml", "yaml"};

}public List> load(String name, Resource resource) throwsIOException {if (!ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", (ClassLoader)null)) {throw new IllegalStateException("Attempted to load " + name + " but snakeyaml was not found on the classpath");

}else{

List> loaded = (newOriginTrackedYamlLoader(resource)).load();if(loaded.isEmpty()) {returnCollections.emptyList();

}else{

List> propertySources = newArrayList(loaded.size());for(int i = 0; i < loaded.size(); ++i) {

String documentNumber= loaded.size() != 1 ? " (document #" + i + ")" : "";

propertySources.add(new OriginTrackedMapPropertySource(name +documentNumber, (Map)loaded.get(i)));

}returnpropertySources;

}

}

}

}

配置这一块就说道这里~~~

下一章来介绍下自定的注解,同时也会结合.NetCore自定义属性标签来比较来时比较说明。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值