我有两个自定义注释,如下所述。
下面是使用2个自定义注释的代码片段。
@CustomAnnotationMain(value = "parent")
public class MainClass{
@CustomAnnotationChild(value = "child1")
public ObjectBuilder getObject1() {
// logic
}
@CustomAnnotationChild(value = "child2")
public ObjectBuilder getObject2() {
// logic
}
}
问题:如何获取所有CustomAnnotationMain注释类的列表以及作为组件一部分可用的所有bean注释信息?
我做了以下操作来获取所有带有@CustomAnnotationKids注释的bean。但是我不确定如何访问bean可用的类。我需要为给定的bean访问@CustomAnnotationMain。
allBuilders = context.getBeansOfType(ObjectBuilder.class);
PS:这不是基于Spring Boot的项目。我只使用Spring核心库。
我做了类似的事情。引入了一个接口Proxyable,需要找到所有带有接口注释的bean或为所有定义的接口创建代理。
https://github.com/StanislavLapitsky/SpringSOAProxy/blob/master/core/src/main/java/org/proxysoa/spring/service/ProxyableScanRegistrar.java
在您的情况下,您应该将Proxyable替换为CustomAnnotationMain。
ClassPathScanningCandidateComponentProvider定义的逻辑可以更改以反映您的过滤器(我只需要那里的接口)。
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
LOG.debug("Registering @Proxyable beans");
// Get the ProxyableScan annotation attributes
Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ProxyableScan.class.getCanonicalName());
if (annotationAttributes != null) {
String[] basePackages = (String[]) annotationAttributes.get("value");
if (basePackages.length == 0) {
// If value attribute is not set, fallback to the package of the annotated class
basePackages = new String[]{((StandardAnnotationMetadata) metadata).getIntrospectedClass().getPackage().getName()};
}
// using these packages, scan for interface annotated with Proxyable
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment) {
// Override isCandidateComponent to only scan for interface
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return metadata.isIndependent() && metadata.isInterface();
}
};
provider.addIncludeFilter(new AnnotationTypeFilter(Proxyable.class));
ControllerFactory factory = getControllerFactory((DefaultListableBeanFactory) registry);
// Scan all packages
for (String basePackage : basePackages) {
for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
try {
Class c = this.getClass().getClassLoader().loadClass(beanDefinition.getBeanClassName());
if (!hasImplementingClass(c, basePackages)) {
//creating missing beans logic is skipped
}
} catch (ClassNotFoundException e) {
throw new SOAControllerCreationException("cannot create proxy for " + beanDefinition.getBeanClassName());
}
}
}
}
}
希望有帮助