Spring-data : Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'userService'

huangapple go评论67阅读模式
英文:

Spring-data : Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'userService'

问题

以下是翻译好的内容:

我刚开始学习spring-boot,当我尝试运行 ``` mvn clean install ``` 命令时,终端给了我这个 **错误** :

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 7.465 s <<< FAILURE! - in com.example.accessingdatamysql.AccessingDataMySqlApplicationTests
[ERROR] contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: 无法加载应用上下文
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 通过字段 'userService' 表达的不满足的依赖;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 通过字段 'mapper' 表达的不满足的依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有符合类型 'com.example.accessingdatamysql.util.UserMapper' 的 Bean 可用:预期至少有 1 个符合自动装配候选的 Bean。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 通过字段 'mapper' 表达的不满足的依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有符合类型 'com.example.accessingdatamysql.util.UserMapper' 的 Bean 可用:预期至少有 1 个符合自动装配候选的 Bean。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有符合类型 'com.example.accessingdatamysql.util.UserMapper' 的 Bean 可用:预期至少有 1 个符合自动装配候选的 Bean。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] AccessingDataMySqlApplicationTests.contextLoads » IllegalState 无法加载...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.677 s
[INFO] Finished at: 2020-10-03T22:37:51+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project accessingdatamysql: 有测试失败。

我已经尝试过多种方法,但无法正确启动它,我在这个状态中困扰了几天。
我添加了项目的各个部分
**AccessingDataMysqlApplication.java**

package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class AccessingDataMysqlApplication {

public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}

}

**MainController.java**

package com.example.accessingdatamysql.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.accessingdatamysql.model.dto.UserDto;
import com.example.accessingdatamysql.service.UserService;

@RestController
public class MainController {

@Autowired
private UserService userService;

@Transactional
@PostMapping(path="/demo/add")
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String email,@RequestParam String surname)
{
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "Saved";
}

@GetMapping("/demo/first")
public UserDto one(@RequestParam String name) {
System.out.print(name);
return userService.findFirstByName(name);
}
}

**UserService.java**

package com.example.accessingdatamysql.service;

import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.dto.UserDto;

@Service
public interface UserService {

UserDto findFirstByName(String name);

void create(UserDto user);

}


**UserServiceImpl.java**

package com.example.accessingdatamysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.dto.UserDto;
import com.example.accessingdatamysql.model.entity.UserEntity;
import com.example.accessingdatamysql.model.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;

@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserRepository userRepository;

@Autowired
UserMapper mapper;

@Override
public UserDto findFirstByName(String name) {
	   UserEntity entity = userRepository.findFirstByName(name);
	return mapper.toDtoMapper(entity);
}

@Override
public void create(UserDto user) {
     UserEntity entity = mapper.toEntityMapper(user);
     userRepository.create(entity);
}

}


**POM**

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0 org.springframework.boot
spring-boot-starter-parent
2.3.4.RELEASE
com.example
accessingdatamysql
0.0.1-SNAPSHOT
project
Demo project for Spring Boot

<properties>
	<java.version>1.8</java
英文:

I am new to spring-boot, when i try to run the mvn clean install the terminal gives me this ERROR:

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 7.465 s &lt;&lt;&lt; FAILURE! - in com.example.accessingdatamysql.AccessingDataMySqlApplicationTests
[ERROR] contextLoads  Time elapsed: 0.001 s  &lt;&lt;&lt; ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;mainController&#39;: Unsatisfied dependency expressed through field &#39;userService&#39;; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;userServiceImpl&#39;: Unsatisfied dependency expressed through field &#39;mapper&#39;; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;com.example.accessingdatamysql.util.UserMapper&#39; available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;userServiceImpl&#39;: Unsatisfied dependency expressed through field &#39;mapper&#39;; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;com.example.accessingdatamysql.util.UserMapper&#39; available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;com.example.accessingdatamysql.util.UserMapper&#39; available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   AccessingDataMySqlApplicationTests.contextLoads &#187; IllegalState Failed to load ...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.677 s
[INFO] Finished at: 2020-10-03T22:37:51+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project accessingdatamysql: There are test failures.

I tried them all a bit but I can't get it started correctly, I've been stuck in this state for several days
I add the various parts of the project
AccessingDataMysqlApplication.java

package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication
public class AccessingDataMysqlApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMysqlApplication.class, args);
  }

}

MainController.java

package com.example.accessingdatamysql.rest;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.accessingdatamysql.model.dto.UserDto;
import com.example.accessingdatamysql.service.UserService;


@RestController
public class MainController {
	
@Autowired 
private UserService userService;

  @Transactional
  @PostMapping(path=&quot;/demo/add&quot;)
  public @ResponseBody String addNewUser (@RequestParam String name
      , @RequestParam String email,@RequestParam String surname) 
  {
 

    UserDto n = new UserDto();
    n.setName(name);
    n.setSurname(surname);
    n.setEmail(email);
    userService.create(n);
	return &quot;Saved&quot;;
  }



 


  @GetMapping(&quot;/demo/first&quot;)
  public UserDto one(@RequestParam String name) {
   System.out.print(name);
  return userService.findFirstByName(name); 
  }
}

UserService.java

package com.example.accessingdatamysql.service;

import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.dto.UserDto;

@Service
public interface UserService {

	UserDto findFirstByName(String name);
	
	void create(UserDto user);
    	
}
  

UserServiceImpl.java

package com.example.accessingdatamysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.dto.UserDto;
import com.example.accessingdatamysql.model.entity.UserEntity;
import com.example.accessingdatamysql.model.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	  private UserRepository userRepository;
	
	@Autowired
    UserMapper mapper;

	@Override
	public UserDto findFirstByName(String name) {
		   UserEntity entity = userRepository.findFirstByName(name);
		   
		return mapper.toDtoMapper(entity);
	}

	@Override
	public void create(UserDto user) {
         UserEntity entity = mapper.toEntityMapper(user);
         
         userRepository.create(entity);
		
	}
 
}

POM

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;2.3.4.RELEASE&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;
	&lt;groupId&gt;com.example&lt;/groupId&gt;
	&lt;artifactId&gt;accessingdatamysql&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name&gt;project&lt;/name&gt;
	&lt;description&gt;Demo project for Spring Boot&lt;/description&gt;

	&lt;properties&gt;
		&lt;java.version&gt;1.8&lt;/java.version&gt;
			&lt;/properties&gt;

	&lt;dependencies&gt;
			&lt;dependency&gt;
			&lt;groupId&gt;org.mapstruct&lt;/groupId&gt;
			&lt;artifactId&gt;mapstruct&lt;/artifactId&gt;
			&lt;version&gt;1.3.1.Final&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;mysql&lt;/groupId&gt;
			&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
			&lt;scope&gt;runtime&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
			&lt;scope&gt;test&lt;/scope&gt;
			&lt;exclusions&gt;
				&lt;exclusion&gt;
					&lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
					&lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
				&lt;/exclusion&gt;
			&lt;/exclusions&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

&lt;/project&gt;

The structure of my project is this:

src-&gt;com-&gt;example-&gt;accessingdatamysql|-----&gt;model
                                     |-----&gt;repo
                                     |-----&gt;util
                                     |-----&gt;service
                                     |-----&gt;rest-----&gt;Main.Controller.java
                                     |-----&gt;AccessingDataMysqlApplication.java

UserMapper.java

package com.example.accessingdatamysql.util;

import org.mapstruct.Mapper;

import com.example.accessingdatamysql.model.dto.UserDto;
import com.example.accessingdatamysql.model.entity.UserEntity;


@Mapper (componentModel = &quot;spring&quot;)
public interface UserMapper {

    UserEntity toEntityMapper (UserDto user);
    
    UserDto toDtoMapper (UserEntity userEntity);
}

I tried to make changes With the MainController, to change the Controller but there are no changes. Entering either @EntityScan or @Component didn't help me in any way

答案1

得分: 1

问题在于 Spring 无法创建名为 com.example.accessingdatamysql.util.UserMapper 的此类型的 Bean。
它声称没有其实现。
请检查该类上的注解。

英文:

The issue is that spring is not able to create a bean of this type: com.example.accessingdatamysql.util.UserMapper
It claims that there are no implementations of it.
Check your annotations on that class.

答案2

得分: 1

我在 UserService 中找到了问题。UserService 使用了 UserMapper 接口,但是 UserMapper 不是一个由 Spring 管理的 bean。因此 @Autowired 注解在 UserMapper 上不起作用。从 UserMapper 中移除 @Autowired,并按照 MapStruct 的指南使用 UserMapper,问题应该会得到解决。

你的代码应该如下所示,在 UserService.java 中:

UserMapper userMapper = Mappers.getMapper(UserMapper.class);

我还发现你遗漏了 MapStruct 的 Maven 插件。你需要添加以下插件使得 MapStruct 生效。你的 pom.xml 文件中的插件部分应该如下所示:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>1.3.1.Final</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

希望这些信息能够帮助你。如果需要进一步的信息,你可以参考以下链接:

英文:

I found the problem in UserService. UserService uses UserMapper interface but UserMapper is not a Spring managed bean. So @Autowired annotation does not work with UserMapper. Remove @Autowired from UserMapper and use UserMapper following MapStruct guidelines and the problem should be solved.

Your code should look like this. In UserService.java

UserMapper userMapper = Mappers.getMapper( UserMapper.class );

I also found that you missed maven plugin for mapstruct. You need to add this plugin for mapstruct to work.
Your plugins section in pom.xml should look like this.

&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
            &lt;version&gt;3.5.1&lt;/version&gt;
            &lt;configuration&gt;
                &lt;source&gt;1.8&lt;/source&gt;
                &lt;target&gt;1.8&lt;/target&gt;
                &lt;annotationProcessorPaths&gt;
                    &lt;path&gt;
                        &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;
                        &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;
                        &lt;version&gt;1.3.1.Final&lt;/version&gt;
                    &lt;/path&gt;
                &lt;/annotationProcessorPaths&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;

Hope this helps. For further information you can look at
https://mapstruct.org/
https://www.baeldung.com/mapstruct

huangapple
  • 本文由 发表于 2020年10月4日 04:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定