maven 在Sping Boot JPA for MySQL中为我的所有类创建Bean时出错?

flvtvl50  于 2024-01-06  发布在  Maven
关注(0)|答案(2)|浏览(183)

我试图设置一个简单的端点来访问MySQL数据库,使用一个MySQL Account()方法,但似乎Sping Boot 无法通过我的所有类连接/创建bean。
下面是代码的详细信息:

MykitchenresourcesApplication

package com.it326.mykitchenresources;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages = "com.it326.mykitchenresources.*")
@EntityScan("com.it326.mykitchenresources.*")  
@EnableJpaRepositories("com.it326.mykitchenresources.*")
public class MykitchenresourcesApplication {

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

}

字符串

账户管理员

package com.it326.mykitchenresources.controllers;

// Imports

@RestController
@RequestMapping("/account")
public class AccountController {

    private final AccountService accountService;

    @Autowired
    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping("/hello")
    public String hello() {
        return "Hello, world!";
    }

    @PostMapping("/create")
    public ResponseEntity<String> createAccount(@RequestBody AccountDTO accountDTO) {
        // Retrieve values from the DTO (Data Transfer Object)
        String name = accountDTO.getName();
        String username = accountDTO.getUsername();
        String password = accountDTO.getPassword();

        // Create the account
        Account createdAccount = accountService.createAccount(name, username, password);

        if (createdAccount != null) {
            return ResponseEntity.status(HttpStatus.CREATED).body("Account created successfully");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create account");
        }
    }
}

账户服务

package com.it326.mykitchenresources.services;

// Imports

@Service
public class AccountService {
    
    @Autowired
    private final AccountDb accountDb;

    public AccountService(AccountDb accountDb) {
        this.accountDb = accountDb;
    }

    public Account createAccount(String name, String username, String password) {
        Account account = new Account();
        account.setName(name);
        account.setUserName(username);
        account.setHashedPassword(hashPassword(password));
        return accountDb.save(account);
    }

    private String hashPassword(String password) {
        // Generate a salt and hash the password using BCrypt
        String salt = BCrypt.gensalt();
        return BCrypt.hashpw(password, salt);
    }
}

AccountDb(我的仓库类)

package com.it326.mykitchenresources.dbs;

// Imports

@Repository
public interface AccountDb extends JpaRepository<Account, Integer> {
    Account findByUsername(String username);
}

账户(我的实体类)

package com.it326.mykitchenresources.entities;

// Imports

@Entity
@Table(name = "accounts")
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "account_id")   
    private int accountId;

    @Column(name = "name", length = 45)
    private String name;

    @Column(name = "username", length = 45)
    private String username;

    @Column(name = "hashed_password", length = 45)
    private String hashedPassword;
    
    // Constructors, getters, setters, etc.
    public Account(){}

    public Account(int accountId, String name, String username, String hashedPassword){
        this.accountId = accountId;
        this.name = name;
        this.username = username;
        this.hashedPassword = hashedPassword;
    }
    
    public int getAccountId() {
        return accountId;
    }
    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUserName() {
        return username;
    }
    public void setUserName(String username) {
        this.username = username;
    }
    public String getHashedPassword() {
        return hashedPassword;
    }
    public void setHashedPassword(String hashedPassword) {
        this.hashedPassword = hashedPassword;
    }
}

应用.属性

spring.datasource.url= // My URL is here.
spring.datasource.username= // Same with my username
spring.datasource.password= // And my password
server.port=8081
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

pom.xml文件

<?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>3.1.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.it326</groupId>
    <artifactId>mykitchenresources</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mykitchenresources</name>
    <description>Backend for myKitchen</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Password Hashing Dependency -->
        <dependency>
            <groupId>org.mindrot</groupId>
            <artifactId>jbcrypt</artifactId>
            <version>0.4</version> <!-- or the latest version available -->
        </dependency>

        <!-- Database Connection Dependencies -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.7.Final</version> <!-- Use the appropriate version -->
        </dependency>
        
        <!-- Testing Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


我试过把我所有的类都放到主应用程序的同一个包中,但似乎这并不能解决我的问题。
我还尝试了不带任何类的mvn clean install,以检查我的主应用程序是否正常工作,它工作得很好。

我得到的日志和错误:

o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - 
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController' defined in file [C:\Users\...\target\classes\com\it326\mykitchenresources\controllers\AccountController.class]: 
Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'accountService' defined in file [C:\Users\...\target\classes\com\it326\mykitchenresources\services\AccountService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'accountDb' defined in com.it326.mykitchenresources.dbs.AccountDb defined in @EnableJpaRepositories declared on MykitchenresourcesApplication: Not a managed type: class com.it326.mykitchenresources.entities.Account


这是我第一次自己建立Sping Boot 项目,所以我可能会错过一些非常明显的东西,并盯着我的脸;任何帮助和指点都将非常感谢!谢谢!

o8x7eapl

o8x7eapl1#

正如在注解中已经指出的,你应该删除hibernate-core的显式依赖。这一个:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.5.7.Final</version> <!-- Use the appropriate version -->
</dependency>

字符串
完成后,你应该检查你的类中使用的所有导入。特别是实体类。不应该有来自javax.persistence包的导入。只有来自jakarta.persistence的导入。否则你会遇到对象不匹配和错误,比如:not a managed type

polkgigr

polkgigr2#

您忘记在AccountService的构造函数中自动连接AccountDB

@Service
public class AccountService {

    private final AccountDb accountDb;

    @Autowired // <-- Added a @Autowired annotation.
    public AccountService(AccountDb accountDb) {
        this.accountDb = accountDb;
    }

    public Account createAccount(String name, String username, String password) {
        Account account = new Account();
        account.setName(name);
        account.setUserName(username);
        account.setHashedPassword(hashPassword(password));
        return accountDb.save(account);
    }

    private String hashPassword(String password) {
        // Generate a salt and hash the password using BCrypt
        String salt = BCrypt.gensalt();
        return BCrypt.hashpw(password, salt);
    }
}

字符串

相关问题