Java Spring Boot VS .NetCore (七) 配置文件

 

Java Spring Boot VS .NetCore (一)來一個簡單的 Hello Worldhtml

Java Spring Boot VS .NetCore (二)實現一個過濾器Filtermysql

Java Spring Boot VS .NetCore (三)Ioc容器處理spring

Java Spring Boot VS .NetCore (四)數據庫操做 Spring Data JPA vs EFCoresql

Java Spring Boot VS .NetCore (五)MyBatis vs EFCore數據庫

Java Spring Boot VS .NetCore (六) UI thymeleaf vs cshtmljson

Java Spring Boot VS .NetCore (七) 配置文件app

Java Spring Boot VS .NetCore (八) Java 註解 vs .NetCore Attribute函數

Java Spring Boot VS .NetCore (九) Spring Security vs .NetCore Securityspring-boot

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中建立方式

一、YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

二、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自定義屬性標籤來比較來時比較說明。

相關文章
相關標籤/搜索