SpringBoot配置文件的加载

本文引用了 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");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值