1. 程式人生 > >[springboot](四)配置檔案+filter

[springboot](四)配置檔案+filter

前言 分散配置是系統必不可少的一部分,將配置引數抽離出來為後期維護提供很大的便利。spring boot 預設支援兩個格式的配置檔案:.properties .yml。 .properties與.yml *.properties屬性檔案;屬於最常見的一種; *.yml是yaml格式的檔案,yaml是一種非常簡潔的標記語言。 在*.properties中定義user.address.stree=hangzhou等價與yaml檔案中的 user: address: stree:hangzhou 從上可以發現yaml層次感更強,具體在專案中選擇那種資原始檔是沒有什麼規定的。 解析 在spring boot中預設會載入 classpath:/,classpath:/config/,file:./,file:./config/ 路徑下以application命名的property或yaml檔案; 引數spring.config.location設定配置檔案存放位置 引數spring.config.name設定配置檔名稱 在啟動工程時會為age隨機生成一個值

random.int(100):10{random.int[0,100]} : 指定範圍的數字 在配置檔案呼叫佔位符 修改配置檔案: userName=liaokailin age=random.int[0,100]remark=hello,mynameis{userName},age is ${age}

修改bean: @Component public class User {

private @Value("${userName:lkl}") String name;
private @Value("${age}") Integer         age;
private @Value("${remark}") String       remark;

執行發現remark答應出: remark=hello,my name is liaokailin,age is 25。 可以發現將name修改為userName,在配置檔案中呼叫name@Valuebean調使@Value,springbootuserName=liaokailinage={random.int[0,100]} remark=hello,my name is

userName,ageis{age} user.address=china,hangzhou

增加user.address=china,hangzhou,為了呼叫該引數來使用@ConfigurationProperties。 User.java @Component @ConfigurationProperties(prefix = “user”) public class User {

private @Value("${userName:lkl}") String name;
private @Value("${age}") Integer         age;
private @Value("${remark}") String       remark;
private String                           address;

使用@ConfigurationProperties需要指定prefix,同時bean中的屬性和配置引數名保持一致。 實體巢狀配置 在User中定義一個Address實體同樣可以快捷配置 User.java @Component @ConfigurationProperties(prefix = “user”) public class User {

private @Value("${userName:lkl}") String name;
private @Value("${age}") Integer         age;
private @Value("${remark}") String       remark;
private String                           address;
private Address                          detailAddress;

Address.java “` public class Address { private String country; private String province; private String city; …

} application.properties` userName=liaokailin age=random.int[0,100]remark=hello,mynameis{userName},age is ${age} user.address=china,hangzhou user.detailAddress.country=china user.detailAddress.province=zhejiang user.detailAddress.city=hangzhou

執行得到 userUser [name=liaokailin, age=57, remark=hello,my name is liaokailin,age is 0, address=china,hangzhou, detailAddress=Address [country=china, province=zhejiang, city=hangzhou]] 1 這種巢狀關係如果通過yaml檔案展示出來層次感會更強。 user: detailAddress: country:china province:zhejiang city:hangzhou

注意在yaml中縮排不要使用TAB 配置集合 一個人可能有多個聯絡地址,那麼地址為集合 User.java @Component @ConfigurationProperties(prefix = “user”) public class User {

private @Value("${userName:lkl}") String name;
private @Value("${age}") Integer         age;
private @Value("${remark}") String       remark;
private String                           address;
private Address                          detailAddress;
private List<Address>                    allAddress = new ArrayList<Address>();

application.properties user.allAddress[0].country=china user.allAddress[0].province=zhejiang user.allAddress[0].city=hangzhou

user.allAddress[1].country=china user.allAddress[1].province=anhui user.allAddress[1].city=anqing

`` 通過下標`表明對應記錄為集合中第幾條資料,得到結果: 1userUser [name=liaokailin, age=64, remark=hello,my name is liaokailin,age is 82, address=china,hangzhou, detailAddress=Address [country=china, province=zhejiang, city=hangzhou], allAddress=[Address [country=china, province=zhejiang, city=hangzhou], Address [country=china, province=anhui, city=anqing]]] 1 如果用yaml檔案表示為: application.yml user: -allAddress: country:china province:zhejiang city:hangzhou -allAddress: country:china province:anhui city:anqing

多配置檔案 spring boot設定多配置檔案很簡單,可以在bean上使用註解@Profile(“development”)即呼叫application-development.properties|yml檔案,也可以呼叫SpringApplication中的etAdditionalProfiles()方法。 例如: package com.lkl.springboot;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Profile;

import com.lkl.springboot.listener.MyApplicationStartedEventListener;

@Profile(“development”) @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication app = new SpringApplication(Application.class); // app.setAdditionalProfiles(“development”); app.addListeners(new MyApplicationStartedEventListener()); app.run(args); } }

也可以通過啟動時指定引數spring.profiles.active。 自定義Filter 我們常常在專案中會使用filters用於錄呼叫日誌、排除有XSS威脅的字元、執行許可權驗證等等。Spring Boot自動添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,並且我們可以自定義Filter。 兩個步驟: 實現Filter介面,實現Filter方法 新增@Configurationz 註解,將自定義Filter加入過濾鏈 @Configuration public class WebConfiguration { @Bean public RemoteIpFilter remoteIpFilter() { return new RemoteIpFilter(); }

@Bean
public FilterRegistrationBean testFilterRegistration() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("MyFilter");
    registration.setOrder(1);
    return registration;
}

public class MyFilter implements Filter {
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request = (HttpServletRequest) srequest;
        System.out.println("this is MyFilter,url :"+request.getRequestURI());
        filterChain.doFilter(srequest, sresponse);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
}