如何修复 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“name”的 bean 时出错?

Posted

技术标签:

【中文标题】如何修复 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“name”的 bean 时出错?【英文标题】:How to fix org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'name'? 【发布时间】:2020-04-26 04:25:14 【问题描述】:

我尝试在 Spring Boot 中与 JPA 建立多对多关系。

Post.java:

@Entity
@Table(name = "post")
public class Post 

    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Id
    @Column(name = "postId")
    private Integer postId;
    @Column(name = "name")
    private String name;
    @ManyToMany
    @JoinTable(name="postTag", joinColumns =  @JoinColumn(name = "postId") , inverseJoinColumns =  @JoinColumn(name = "tagId") )
    private List<Tag> tags = new ArrayList<Tag>();

    public Post() 
    

    public Integer getPostId() 
        return postId;
    

    public void setPostId(Integer id) 
        this.postId = id;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public List<Tag> getTags() 
        return tags;
    

    public void setTags(List<Tag> tags) 
        this.tags = tags;
    


标签.java:

 @Entity
@Table(name = "Tag")
public class Tag 

    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Id
    @Column(name = "tagId")
    private Integer tagId;
    @Column(name = "name")
    private String name;
    @ManyToMany(cascade=CascadeType.ALL, mappedBy = "tags")
    private List<Post> posts = new ArrayList<Post>();

    public Tag() 
        count = 1;
    

    public Integer getTagId() 
        return tagId;
    

    public void setTagId(Integer id) 
        this.tagId = id;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public List<Post> getPosts() 
        return posts;
    

    public void setPosts(List<Post> posts) 
        this.posts = posts;
    


PostService.java:

@Service
public class PostService 

    private PostRepository postRepository;

    @Autowired
    public void setPostRepository(PostRepository postRepository) 
        this.postRepository = postRepository;
       

    public Post getPostById(Integer id) 
        return postRepository.findByPostId(id);
    

    @PostConstruct
    public void create() 
        Tag tag1 = new Tag();
        tag1.setName("tag1");

        Post post = new Post();
        post.setName("post");
        post.getTags().add(tag1);
        postRepository.save(post);

        Post dbPost = postRepository.findByPostId(post.getPostId());
        System.out.println(post.getName() + " -> " + post.getTags() + "  |  " 
        + dbPost.getName() + " -> " + dbPost.getTags());

    

PostRepository.java:

public interface PostRepository extends CrudRepository<Post, Integer> 

    List<Post> findAll();

    Post findByPostId(Integer id);


控制台上的完整错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through method 'setTagService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tagService': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at com.hunor.FirstProjectApplication.main(FirstProjectApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tagService': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:160) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:715) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.NullPointerException: null
    at com.hunor.service.TagService.create(TagService.java:48) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_231]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_231]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_231]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    ... 31 common frames omitted

没有关系(删除List&lt;Tag&gt; tagsList&lt;Post&gt; posts 和相关部分)完全正常,mysql 数据库和bean 没有问题。但是由于关系,我得到了上面的错误。

【问题讨论】:

tagService 在哪里创建/初始化? 失败的根本原因是TagService.java:48处的NullPointerException。 【参考方案1】:

PostService 的方法 create() 在创建 bean 时执行 (@PostConstruct),它试图使用仅稍后初始化的 PostRepository bean (setter injection as it is @Autowired) .

NPE 在第 48 行:com.hunor.service.TagService.create(TagService.java:48)

【讨论】:

非常感谢,我删除了 PostConstruct 注释,并从控制器调用该方法。这可以解决问题。我发现了一个新错误,在将“Tag tag1”添加到“post.getTags()”之前,我应该使用“tagRepository.save(tag1)”保存“tag1”。再次感谢您,祝您有美好的一天!

以上是关于如何修复 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“name”的 bean 时出错?的主要内容,如果未能解决你的问题,请参考以下文章

如何修复 LockObtainFailedException:锁定获取超时?

如何在 Grails 3 中捕获“org.springframework.web.multipart.MultipartException”

如何使用 org.springframework.jdbc.object 实现可重用的 ddl 语句?

如何在 org.springframework.jdbc.CannotGetJdbcConnectionException 上记录 JDBC 连接信息

如何解决 org.springframework.web.util.NestedServletException:请求处理失败;使用 SAML

整个 org.springframework 的 Maven 依赖项