1. 程式人生 > >springboot專案配置檔案的讀取高階用法

springboot專案配置檔案的讀取高階用法

配置檔案

web:
  my_name: mqs
  tags: aaa,bbb,ccc,ddd
  like: 學習

配置檔案對應的實體類

package com.test.demo.pojo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: Mqs
 * @Date: 2018/11/6 14:17
 * @Description:
 */
@ConfigurationProperties(prefix = "web")
@Data
public class WebPropertie {

    private String myName;
    private String[] tags;
    private String like;
}

config類

package com.test.demo.config;

import com.test.demo.pojo.WebPropertie;
import javassist.tools.web.Webserver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: Mqs
 * @Date: 2018/11/6 14:22
 * @Description:
 */
@Configuration
@EnableConfigurationProperties(WebPropertie.class)
public class WebConfig {

    private final WebPropertie webPropertie;

    public WebConfig(WebPropertie webPropertie) {
        this.webPropertie = webPropertie;
    }

    @Bean
    public WebService webService(){
        WebService webService = new WebService();
        webService.setWebPropertie(webPropertie);
        return webService;
    }
}

service檔案

package com.test.demo.config;

import com.test.demo.pojo.WebPropertie;

/**
 * @Author: Mqs
 * @Date: 2018/11/6 14:25
 * @Description:
 */
public class WebService {

    private WebPropertie webPropertie;

    public WebPropertie getWebPropertie() {
        return webPropertie;
    }

    public void setWebPropertie(WebPropertie webPropertie) {
        this.webPropertie = webPropertie;
    }
}

測試類

    @Autowired
    private WebService webService;
    @RequestMapping("/web2")
    public String testWeb2(){
        WebPropertie webPropertie = webService.getWebPropertie();
        String str = Arrays.toString(webPropertie.getTags()) + "----->>>" + webPropertie.getLike() + "----->>>" + webPropertie.getMyName();
        return str;
    }