Java 使用自定义批注时发生依赖项注入错误
我正在尝试使用springboot应用程序中的以下代码基于注释参数初始化bean。但是我没有得到任何符合条件的bean错误。你知道可能是什么问题吗Java 使用自定义批注时发生依赖项注入错误,java,jakarta-ee,annotations,cdi,inject,Java,Jakarta Ee,Annotations,Cdi,Inject,我正在尝试使用springboot应用程序中的以下代码基于注释参数初始化bean。但是我没有得到任何符合条件的bean错误。你知道可能是什么问题吗 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [DemoClient] found for dependency: expected at least 1 bean which qualifi
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [DemoClient] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject(), @DemoAnnotation(name=demo)}
自定义注释
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public @interface DemoAnnotation {
String name() default "";
}
接口
public interface DemoClient {
}
恳求
工厂
import javax.enterprise.inject.Produces;
public class DemoClientFactory {
@Produces
public DemoClient createDemoClient(InjectionPoint injectionPoint) {
DemoAnnotation demoAnnotation = injectionPoint.getAnnotated().getAnnotation(DemoAnnotation.class);
if (demoAnnotation != null) {
System.out.println("NAME " + demoAnnotation.name());
}
// can return different Impl's based on annotation parameter 'name'
return new DemoClientImpl();
}
}
试验
这是JavaEE而不是Spring,我将删除我的答案。您的应用程序中似乎有SpringJAR(和配置)。你真的在任何地方使用Spring框架吗?你把Spring框架和CDI这两种东西混在一起了。对于Spring,CDI的等价物是
@products
在@Configuration
类中的@Bean
,您的demo注释应该是@Qualifier,producer方法应该使用与注入目标相同的demo注释进行注释,以便容器可以匹配这两个。
import javax.enterprise.inject.Produces;
public class DemoClientFactory {
@Produces
public DemoClient createDemoClient(InjectionPoint injectionPoint) {
DemoAnnotation demoAnnotation = injectionPoint.getAnnotated().getAnnotation(DemoAnnotation.class);
if (demoAnnotation != null) {
System.out.println("NAME " + demoAnnotation.name());
}
// can return different Impl's based on annotation parameter 'name'
return new DemoClientImpl();
}
}
@Inject
@DemoAnnotation(name = "demo")
private DemoClient demoClient;