com.project.api.graphql.service.GraphQLService中的构造函数的参数0需要找不到类型为'java.lang.String'的bean

时间:2020-10-19 20:17:07

标签: java spring spring-boot graphql

我是Spring Boot的新手,我想知道这个错误消息。

我正在尝试创建一个GraphQL类以连接到各种GraphQL配置,并且我想将一个值传递给构造函数(最终是针对我的类路径):

public class ArticleResource {

    @Autowired
    GraphQLService graphQLService = new GraphQLService("classpath:articles.graphql");
    ... other code
}

public class GraphQLService {

    public GraphQLService(String value) {
        System.out.println(value);
    }
    ... other code with @Autowired & @PostConstruct annotations
}

我正在使用一个如何将GraphQL连接到Spring Boot的示例,并且在几个地方都使用了@Autowired批注以及@PostConstruct。我觉得其中之一导致了我所看到的问题。

完整错误如下:

Description:

Parameter 0 of constructor in com.project.api.graphql.service.GraphQLService required a bean of type 'java.lang.String' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

我该如何解决?我不能将自定义构造函数与Autowired或PostConstruct批注一起使用吗?

2 个答案:

答案 0 :(得分:2)

就像评论中已经提到的michalk一样,您在ArticleResource中滥用了依赖项注入-我强烈建议您通读spring的文档here

基本上是这样:您要满足的依赖关系,在这种情况下,GraphQLService具有一个构造函数,其中一个参数的类型为String。 Spring将尝试注入它,但是由于在项目中的任何地方都没有定义String类型的@Bean,所以它将失败,并显示错误消息。

在您的情况下更有意义的是定义一个@Configuration类,并从例如application.properties中注入String值,如下所示:

@Configuration
public class GraphQLConfig {

    @Bean
    public GraphQLService graphQLService(@Value("${classpath.value}") String valueReadFromAppProperties) {
        return new GraphQLService(valueReadFromAppProperties);
    }
}

,然后将以下内容添加到您的 application.properties 文件中:

classpath.value=classpath:articles.graphql

最后在 ArticleResource 中注入服务实例时:

public class ArticleResource {

    @Autowired
    GraphQLService graphQLService;
    ... other code
}

尽管可以通过使用构造函数注入而不是字段注入来改进它:

public class ArticleResource {

    private GraphQLService graphQLService;

    public ArticleResource(GraphQLService graphQLService) {
        this.graphQLService = graphQLService;
    }
}

答案 1 :(得分:0)

首先,有关依赖注入的一些信息。如果您使用Spring DI(依赖关系注入),则永远不要使用new关键字来创建“ bean”依赖关系的实例。让Spring为您服务。 另一个建议是使用有用的名称。名称“值”是不好的,因为值可以是一切。命名所有内容,使其具有有意义的名称。

您提供的代码示例不完整。可能您的GraphQLService类中具有@Service批注。因为那个Spring试图在启动时启动服务bean。因为您在该类的构造函数中定义了String,所以Spring尝试自动关联该依赖关系。一个简单的字符串不是已知的bean,因为您会收到错误消息。

请阅读Spring文档,这是如何工作的。也许还会去看spring-data,阅读文档并看一些例子。这为您很好地概述了如何使用Spring解决这类问题。

相关问题