提问者:小点点

Spring 引导@Mapper Bean 创建问题:应用程序无法启动。错误:考虑定义一个类型的 bean


我是 spring 的新手,当我尝试对我的项目进行 mvn 全新安装时,会出现此问题:

错误

***************************
APPLICATION FAILED TO START
***************************

**Description**:

Field userService in com.example.accessingdatamysql.rest.MainController required a bean of type 'com.example.accessingdatamysql.service.UserService' 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 'com.example.accessingdatamysql.service.UserService' in your configuration.

问题是在MainController中有“UserService”的导入:

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); 
  }
}
  

这可能是一件微不足道的事情,但我无法绕过这个问题,下面我插入“用户服务”和 MainStart

UserService.java

package com.example.accessingdatamysql.service;

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

public interface UserService {

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

更新:我插入了UserServiceImpl和新的main和Mapper,但出现了新的错误。

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);
        
    }
 
}

访问数据MysqlApplication.java

package com.example;

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(scanBasePackages = { "com.example.accessingdatamysql",
"com.example.accessingdatamysql.util"})
public class AccessingDataMysqlApplication {

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

}

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 = "spring")
public interface UserMapper {

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

新错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field mapper in com.example.accessingdatamysql.service.UserServiceImpl required a bean of type 'com.example.accessingdatamysql.util.UserMapper' 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 'com.example.accessingdatamysql.util.UserMapper' in your configuration.

聚 甲醛

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>accessingdatamysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>project</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
            </properties>

    <dependencies>
            <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


共2个答案

匿名用户

使用 @Service@Component 批注 UserService 类实现 [如 UserServiceImpl.java]。还要确保此类位于子包中。

这是您的主类包:com.example.accessingdatamysql 您的UserService类和所有其他类应保存在类似:com.example.accessingdatamysql.xxxxxxx的包中。确保遵循此策略。

另外,删除主类上不必要的注释。@SpringBootApplication注释等效于使用以下 3 个:

  1. @配置,
  2. @EnableAutoConfiguration和
  3. @ComponentScan带属性。

这就足够了:

@SpringBootApplication (scanBasePackages = "com.example.accessingdatamysql")

并且在自动连接任何豆子注入时不要保持间隙。这不会造成任何伤害。但是您的代码应该正确组织并完成缩进。

同时替换以下内容:

 @Autowired 
         
private UserService userService;

有了这个:

 @Autowired          
 private UserService userService;

更新-1

在修复了Spring启动配置后,进行一次专业的干净安装。

mvn干净安装

更新-2

Mapper的bean不完全符合Spring bean的条件。您需要使用以下插件编译您的项目(请参阅我使用的第二个插件)。

<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>
            <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>
                <compilerArgs>
                    <compilerArg>
                        -Amapstruct.defaultComponentModel=spring
                    </compilerArg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>

然后,您需要按如下方式修复您的UserDto.java(更改时间戳变量的类型,否则映射器将失败):

import java.sql.Timestamp;




private Timestamp timestamp;

public Timestamp getTimestamp() {
    return timestamp;
}

public void setTimestamp(Timestamp timestamp) {
    this.timestamp = timestamp;
}

您的主类应该只有这个:@SpringBootApplication(scanBasePackages="com. example.access ingdatamysql"),没有其他注释。

然后保存您的项目。然后运行:mvn clean install-X

使您的包结构如下:

您的课程安排如下:

匿名用户

你需要定义一个 bean 让 Spring 使用它们,比如 DI(依赖注入)@Autowired在这种情况下。

有多种方法可以定义bean,但在您的情况下,在服务类上使用@Service注释,以便Spring可以在初始化期间找到它。

并且您不需要声明< code>@ComponentScan批注,< code > @ spring boot application 会处理所有事情。

正如@Som所说,你需要实现你的Userservice类,因为它是接口,还没有实现的类。

尝试删除< code>@ComponentScan批注,并实现< code>UserService接口,如下所示

@Service
public class UserServiceImpl implements UserService{
    // the rest of the code
}