如何让Spring Bean依赖Feign Client Bean创建?懒加载问题求助
问题根源:Feign Client默认是懒加载模式,容器启动阶段不会实例化它的Bean,所以@ConditionalOnBean(GoogleTokenFeignClient.class)检查时找不到对应的Bean实例,导致GoogleAuthenticationProvider无法被创建。
以下是可行的解决方法:
给Feign Client关闭懒加载
在GoogleTokenFeignClient的@FeignClient注解里添加lazy = false属性(Spring Cloud OpenFeign 3.0及以上版本支持),强制容器启动时就实例化该Bean:@ConditionalOnProperty(name = "google.token.url") @FeignClient(name = "google-token-feign-client", url = "${google.token.url}", lazy = false) public interface GoogleTokenFeignClient { // 接口方法 }这样容器启动时就会创建
GoogleTokenFeignClient的Bean实例,@ConditionalOnBean就能检测到,进而创建GoogleAuthenticationProvider。给GoogleAuthenticationProvider添加双重条件
既然GoogleAuthenticationProvider的创建本来就依赖google.token.url配置,直接给它也加上@ConditionalOnProperty注解,同时保留@ConditionalOnBean,双重保障条件触发:@Slf4j @Component @ConditionalOnProperty(name = "google.token.url") @ConditionalOnBean(GoogleTokenFeignClient.class) public class GoogleAuthenticationProvider { // 类实现 }配合上面的
lazy = false,就能确保配置存在时,Feign Client先被实例化,再创建这个Provider。用@DependsOn显式指定依赖顺序
在GoogleAuthenticationProvider上添加@DependsOn注解,指定它必须在google-token-feign-client这个Bean之后创建:@Slf4j @Component @ConditionalOnBean(GoogleTokenFeignClient.class) @DependsOn("google-token-feign-client") public class GoogleAuthenticationProvider { // 类实现 }这个方法可以强制容器优先创建Feign Client的Bean,不过要注意Feign Client的Bean名称要和
@FeignClient的name属性一致,这里就是google-token-feign-client。
内容的提问来源于stack exchange,提问作者leon

