Spring Boot微服务的配置代码重复问题



有没有办法创建一个spring配置类并将其用于我的所有微服务?

例如,我必须复制以下配置类,并将其粘贴到我的所有微服务中,这意味着当我想做一个小的更改时,我必须通过所有微服务编辑同一个类。

我已经调查过了,我能找到的最多的方法是创建一个具有所有公共类的模块,并通过pom将其导入我的微服务中,结果是,当我想要获得SecurityContextHolder.getContext((时,这对于上下文问题是空的,我不太清楚如何给出解决方案,也不知道还有什么其他选择。

@Configuration
public class FeignGlobalConfiguration {
@Bean
public ErrorDecoder errorDecoder() {
return new RetrieveMessageErrorDecoder();
}
@Bean
public RequestInterceptor requestInterceptor(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return requestTemplate -> {
requestTemplate.header(JwtClaims.USERNAME, authentication.getPrincipal().toString());
requestTemplate.header(JwtClaims.CLIENT, authentication.getDetails().toString());
requestTemplate.header(JwtClaims.TOKEN, authentication.getCredentials().toString());
requestTemplate.header(JwtClaims.ROLES, authentication.getAuthorities().toString());
};
}
}

问题在于您的bean定义。

当bean只被构造一次时,就会调用Authentication authentication = SecurityContextHolder.getContext().getAuthentication();行。之后使用参考(在构建时可能是null

要解决此问题,请在lambda中移动该tline,以便在每次处理请求时对其进行求值。

@Bean
public RequestInterceptor requestInterceptor(){
return requestTemplate -> {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
requestTemplate.header(JwtClaims.USERNAME, authentication.getPrincipal().toString());
requestTemplate.header(JwtClaims.CLIENT, authentication.getDetails().toString());
requestTemplate.header(JwtClaims.TOKEN, authentication.getCredentials().toString());
requestTemplate.header(JwtClaims.ROLES, authentication.getAuthorities().toString());
};
}

最新更新