【问题标题】:Spring cannot create define a bean of abstract class in the configurationSpring无法在配置中创建定义抽象类的bean
【发布时间】:2021-10-18 08:42:11
【问题描述】:
public abstract class AbstractMapper<T> implements Function<SomeProducts, T> {

private final ABC abc;
private final XYZ xyz;

constructor()

some abstract methods

我有这个抽象类的两个实现

@Component
public class ProductDTOMapper extends AbstractMapper<Product> {

    constructor()

    @Override
    public Product apply(final SomeProducts products) {
        return Product.builder()
            .id()
            .build();
    }

抽象类的第二个实现

@Component
    public class CustomerDTOMapper extends AbstractMapper<CustomerDocument> {
    
        constructor()
    
        @Override
        public CustomerDocument apply(final SomeProducts products) {
            return CustomerDocument.builder()
                .id()
                .build();
        }

我使用 lombok 构建 CustomerDocument 和 Product:

@Data
@Builder
@Type("typeA")
public class CustomerDocument {

some attributes

}

第二个builder-class:

@Data
@Builder
@Type("typeB")
public class Product {

some attributes

}

在我的控制器中,我有两个映射器的实例:

@AllArgsConstructor
@RestController
@RequestMapping
public class ZController {

    private final AbstractMapper<Product> productDTOMapper;
    private final AbstractMapper<CustomerDocument> customerDTOMapper;

当我启动应用程序时,我得到这个错误:

Parameter 1 of constructor in ZController required a bean of type 'x.y.z.rest.mapper.AbstractMapper' that could not be found.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'zController' defined in file [/path/to/controller/rest/controller/ZController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'x.y.z.rest.mapper.AbstractMapper<rest.dto.product.CustomerDocument>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1354)

【问题讨论】:

  • 你试过用具体的Java类名作为控制器中的字段类型吗?即私有最终 CustomerDTOMapper customerDTOMapper;

标签: java spring spring-boot javabeans lombok


【解决方案1】:

看看这个:

@AllArgsConstructor
@RestController
@RequestMapping
public class ZController {

    private final ProductDTOMapper productDTOMapper;
    private final CustomerDTOMapper customerDTOMapper;

如果你想用超类打字 尝试使用字段依赖注入而不是构造函数 DI,并使用 @Qualifier 和 @Autowired 注释的混合。

问候,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多