簡體   English   中英

Spring不能在配置中創建定義抽象類的bean

[英]Spring cannot create define a bean of abstract class in the configuration

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

}

第二個建造者類:

@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)

看看這個:

@AllArgsConstructor
@RestController
@RequestMapping
public class ZController {

    private final ProductDTOMapper productDTOMapper;
    private final CustomerDTOMapper customerDTOMapper;

如果您想使用超類鍵入,請嘗試使用字段依賴注入而不是構造函數 DI,並混合使用@Qualifier@Autowired注釋。

問候,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM