[springboot](四)配置文件+filter

版权声明:本文为博主原创文章,未经博主允许不得转载。有任何问题请邮件联系[email protected] https://blog.csdn.net/drdongshiye/article/details/82717586

前言
分散配置是系统必不可少的一部分,将配置参数抽离出来为后期维护提供很大的便利。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随机生成一个值
r a n d o m . i n t ( 100 ) : 10 {random.int[0,100]} : 指定范围的数字
在配置文件调用占位符
修改配置文件:
userName=liaokailin
age= r a n d o m . i n t [ 0 , 100 ] r e m a r k = h e l l o , m y n a m e i s {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,在配置文件中调用 n a m e @ V a l u e b e a n 使 @ V a l u e , s p r i n g b o o t u s e r N a m e = l i a o k a i l i n a g e = {random.int[0,100]}
remark=hello,my name is u s e r N a m e , a g e i s {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= r a n d o m . i n t [ 0 , 100 ] r e m a r k = h e l l o , m y n a m e i s {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
    }
}

}
更多参考:http://www.cnblogs.com/ityouknow/p/5730412.html

猜你喜欢

转载自blog.csdn.net/drdongshiye/article/details/82717586