Java Spring Boot VS .NetCore (一)來一個簡單的 Hello World
Java Spring Boot VS .NetCore (二)實現一個過濾器Filter
Java Spring Boot VS .NetCore (三)Ioc容器處理
Java Spring Boot VS .NetCore (四)數據庫操作 Spring Data JPA vs EFCore
Java Spring Boot VS .NetCore (五)MyBatis vs EFCore
Java Spring Boot VS .NetCore (六) UI thymeleaf vs cshtml
Java Spring Boot VS .NetCore (七) 配置文件
Java Spring Boot VS .NetCore (八) Java 注解 vs .NetCore Attribute
Java Spring Boot VS .NetCore (九) Spring Security vs .NetCore Security
Java Spring Boot VS .NetCore (十) Java Interceptor vs .NetCore Interceptor
Java Spring Boot VS .NetCore (十一)自定義標簽 Java Tag Freemarker VS .NetCore Tag TagHelper
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 都是能夠被直接使用的,只需要把 配置文件映射到類的屬性里面,代碼如下
@Component public class PropertiesConfig { @Value("${Spring.datasource.url}") private String database; public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } }
如果世界使用的application.yml 能夠自動被填充的配置資源里面,寫法給上面樣就能拿到配置
我這里自定義一個yml 如:test.yml
這里需要添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
重新構建后,我新建一個class ,這里需要說明的就是 @ProtertySource 指定yml的路徑 需要注意是的 classpath 這個指向的地址,是打包后的目錄,調試的時候肯定找不到對應路徑目錄的文件需要自己配置下,否則就放在下圖的目錄結構
@Component @PropertySource(value = "classpath:/test.yml") @ConfigurationProperties(prefix = "spring1") public class YMLConfig { public String getUrl1() { return url1; } public void setUrl1(String url1) { this.url1 = url1; } @Value("${url1}") private String url1;
使用通過注解 @Autowired \ @Resource 都可以
//測試yml配置 @Autowired private YMLConfig ymlConfig; @Test public void testYmlConfig() { System.out.print(ymlConfig.getUrl1()); }
得到了我們想要的結果,下面在來說下.NetCore中的配置使用情況
.NetCore 配置文件
.NetCore提供了json 、xml 的方式來實現配置,這里我以json 來舉個例子看下使用方式
默認也有一個appsettings.json 的文件,在不使用自定義配置的情況下,系統會加載這個配置文件 ,那么如果要把配置文件映射到class里面需要怎么處理呢?
下來創建一個配置類
public class AuthorityConfig { 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<AuthorityConfig>(Configuration.GetSection("AuthorityConfig"));
根據節點位置配置關聯的類,需要使用的時候通過構造函數注入即可
如果需要添加自定義的配置,我們使用啟動類的構建來創建相關路徑下的相關文件綁定到配置中Configuration 最后通過 Configuration 來綁定 Class之間的關系
public Startup(IConfiguration configuration, IHostingEnvironment env) { var configurationbuilder = new ConfigurationBuilder() .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<Properties>, InitializingBean { private boolean singleton = true; @Nullable private Properties properties; public YamlPropertiesFactoryBean() { } public void setSingleton(boolean singleton) { this.singleton = singleton; } public boolean isSingleton() { return this.singleton; } public void afterPropertiesSet() { if (this.isSingleton()) { this.properties = this.createProperties(); } }
沒有異常,而且是單例
看下第二種的源碼,拋出了IO異常,在找不到文件目錄文件的情況下會拋出異常
public class YamlPropertySourceLoader implements PropertySourceLoader { public YamlPropertySourceLoader() { } public String[] getFileExtensions() { return new String[]{"yml", "yaml"}; } public List<PropertySource<?>> load(String name, Resource resource) throws IOException { 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<Map<String, Object>> loaded = (new OriginTrackedYamlLoader(resource)).load(); if (loaded.isEmpty()) { return Collections.emptyList(); } else { List<PropertySource<?>> propertySources = new ArrayList(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))); } return propertySources; } } } }
配置這一塊就說道這里~~~
下一章來介紹下自定的注解,同時也會結合.NetCore自定義屬性標簽來比較來時比較說明。