本文引用了 https://blog.csdn.net/xtj332/article/details/80946519
场景:
一个由多模块构成的spring boot maven项目,有A,B,C三个子项目,也就是三个jar包,其中A作为公共依赖,建立了公用的权限拦截器配置,有自定义配置文件需要加载
问题:
@Bean
@ConfigurationProperties(prefix = "jwt.config")
public JwtUtil commonJwtUtil(){
return new JwtUtil();
}
在A项目resource下建立application.yml 发现配置不生效,获取不到配置文件信息
原因:
A/B/C三个项目的yaml文件都在自己项目的 resource文件下面,在B引用了A的时候,相当于相同目录下有两个一模一样的yaml文件,此时B的yaml文件会屏蔽掉A文件的yaml文件。 注意:这里是整个文件屏蔽,并不是说屏蔽相同的配置。
解决方案:
将A中的yaml文件放置在config下面。
下面图片来自springBoot官网:
自定义配置文件读取
方式1:
@Component
@ConfigurationProperties(prefix="custom") // 用来指定properties配置文件中的key前缀
@PropertySource("classpath:config/custom.properties") //配置文件所在位置
public class CustomProperties {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
方式2
@Configuration
@ConditionalOnWebApplication
@PropertySource("classpath:config/config.properties")
public class AuthorityConfig implements WebMvcConfigurer {
//public class AuthorityConfig extends WebMvcConfigurationSupport {
// spring.factories 配置的自动扫描WebMvcConfigurationSupport实现类 不加载addInterceptors方法
@Bean
@ConfigurationProperties(prefix = "jwt.config")
public JwtUtil commonJwtUtil(){
return new JwtUtil();
}
@Bean
public AuthorityInterceptor authInterceptor(){
return new AuthorityInterceptor();
}
@Bean
public SecurityUtils securityUtils(){
return new SecurityUtils();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/**/login");
}
}