java注解@FeignClient修饰的类路径不在spring boot入口类所在的包下,有哪几种处理方式?

一、注解@EnableFeignClients

修饰在spring boot入口类,使得openfeign的@FeignClient注解生效。

我们进一步看看注解@EnableFeignClients的使用方式。

String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Class<?>[] clients() default {};

java注解@FeignClient修饰的类路径不在spring boot入口类所在的包下,有哪几种处理方式?_第1张图片

  • 其实已经能满足我们的需求了,但是,很多业务方在引用的时候,往往是懒得去配置。

像下面这样,多写一个配置参数就算输了。

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringCloudApplication
@EnableFeignClients
public class UserServiceApplication {
	public static void main(String[] args) {
		SpringApplication.run(UserServiceApplication.class, args);
	}
}

你本来写好了使用文档,像下面这样使用:

// AuthServiceClient类所在的包名是com.xxx.ddd.jwt.feign
// 当前用户服务的@FeignClient所在包路径是com.xxx.user.service.feign
@SpringCloudApplication
@EnableFeignClients(basePackages = {
          com.xxx.user.service.feign,
          com.xxx.ddd.jwt.feign
      })
 public class UserServiceApplication {
	public static void main(String[] args) {
		SpringApplication.run(UserServiceApplication.class, args);
	}
}
  • 可惜,使用的人,都嫌弃这配置过于多了,压根就不想关心@EnableFeignClients的属性应该写些啥。

所以,本文就简单说下,推荐的一个方式,让使用方不用去关心额外的包路径。

二、类的结构

  • com.xxx.ddd.jwt
    • JwtFeignPackageClass.java
    • feign
      • AuthServiceClient.java

保证注解@EnableFeignClients必须攘括了@FeignClient的包路径。

java注解@FeignClient修饰的类路径不在spring boot入口类所在的包下,有哪几种处理方式?_第2张图片

三、AuthServiceClient.java

package com.xxx.ddd.jwt.feign;

import org.springframework.cloud.openfeign.FeignClient;

@FeignClient(name = "auth-service")
public interface AuthServiceClient {
    // TODO 写你自己的接口
}

四、JwtFeignPackageClass.java

注意,该类的路径是在@FeignClient的包路径下,或者其上一级包路径。

package com.xxx.ddd.jwt;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * jwt feign注解生效的包路径.
 *
 * @author xxx
 */
@EnableFeignClients
public class JwtFeignPackageClass {
}

五、总结

  • org.springframework.cloud.openfeign.FeignClientsRegistrar
class FeignClientsRegistrar
		implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware{

}

梳理下它的主要代码

@Override
	public void registerBeanDefinitions(AnnotationMetadata metadata,
			BeanDefinitionRegistry registry) {
		registerDefaultConfiguration(metadata, registry);
		registerFeignClients(metadata, registry);
	}
  • 扫描注解EnableFeignClients的类所在包下的所有注解FeignClient
	public void registerFeignClients(AnnotationMetadata metadata,
			BeanDefinitionRegistry registry) {
		ClassPathScanningCandidateComponentProvider scanner = getScanner();
		scanner.setResourceLoader(this.resourceLoader);

		Set<String> basePackages;

		Map<String, Object> attrs = metadata
				.getAnnotationAttributes(EnableFeignClients.class.getName());
		AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
				FeignClient.class);
		final Class<?>[] clients = attrs == null ? null
				: (Class<?>[]) attrs.get("clients");
		if (clients == null || clients.length == 0) {
			scanner.addIncludeFilter(annotationTypeFilter);
			basePackages = getBasePackages(metadata);
		}
		else {
			final Set<String> clientClasses = new HashSet<>();
			basePackages = new HashSet<>();
			for (Class<?> clazz : clients) {
				basePackages.add(ClassUtils.getPackageName(clazz));
				clientClasses.add(clazz.getCanonicalName());
			}
			AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
				@Override
				protected boolean match(ClassMetadata metadata) {
					String cleaned = metadata.getClassName().replaceAll("\\$", ".");
					return clientClasses.contains(cleaned);
				}
			};
			scanner.addIncludeFilter(
					new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
		}

		for (String basePackage : basePackages) {
			Set<BeanDefinition> candidateComponents = scanner
					.findCandidateComponents(basePackage);
			for (BeanDefinition candidateComponent : candidateComponents) {
				if (candidateComponent instanceof AnnotatedBeanDefinition) {
					// verify annotated class is an interface
					AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
					AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
					Assert.isTrue(annotationMetadata.isInterface(),
							"@FeignClient can only be specified on an interface");

					Map<String, Object> attributes = annotationMetadata
							.getAnnotationAttributes(
									FeignClient.class.getCanonicalName());

					String name = getClientName(attributes);
					registerClientConfiguration(registry, name,
							attributes.get("configuration"));

					registerFeignClient(registry, annotationMetadata, attributes);
				}
			}
		}
	}
  • 拼接对象FeignClientFactoryBean的属性,利用BeanDefinitionReaderUtils.registerBeanDefinition注册到spring容器
	private void registerFeignClient(BeanDefinitionRegistry registry,
			AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
		String className = annotationMetadata.getClassName();
		BeanDefinitionBuilder definition = BeanDefinitionBuilder
				.genericBeanDefinition(FeignClientFactoryBean.class);
		validate(attributes);
		definition.addPropertyValue("url", getUrl(attributes));
		definition.addPropertyValue("path", getPath(attributes));
		String name = getName(attributes);
		definition.addPropertyValue("name", name);
		String contextId = getContextId(attributes);
		definition.addPropertyValue("contextId", contextId);
		definition.addPropertyValue("type", className);
		definition.addPropertyValue("decode404", attributes.get("decode404"));
		definition.addPropertyValue("fallback", attributes.get("fallback"));
		definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

		String alias = contextId + "FeignClient";
		AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
		beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);

		// has a default, won't be null
		boolean primary = (Boolean) attributes.get("primary");

		beanDefinition.setPrimary(primary);

		String qualifier = getQualifier(attributes);
		if (StringUtils.hasText(qualifier)) {
			alias = qualifier;
		}

		BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
				new String[] { alias });
		BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
	}

openfeign的@FeignClient封装了http请求的入参和出参,并且支持okhttp/httpclient/HttpsURLConnection等调用方式。

你可能感兴趣的:(java,spring,boot,开发语言)