应用程序运行失败org.springframework.beans.factory.UnsatisfiedDependencyException:创建bean时出错

问题描述 投票:0回答:1

VS代码运行出错

启动 ApplicationContext 时出错。要显示条件评估报告,请在启用“调试”的情况下重新运行应用程序。 2024-05-04T20:04:39.029-07:00错误27384 --- [goblinhorde] [restartedMain] o.s.boot.SpringApplication:应用程序运行失败

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“characterController”的bean时出错:通过字段“cService”表示的依赖关系不满足:创建名称为“characterService”的bean时出错:通过字段“cRepo”表示的依赖关系不满足:创建bean时出错名称“characterRepository”在 com.goblinhorde.goblinhorde.repositories.CharacterRepository 中定义,在 JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration 上声明的 @EnableJpaRepositories 中定义:不是托管类型:类 com.goblinhorde.goblinhorde.models.Characters 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:787) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:767) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) ~[spring-beans-6.1.6.jar:6.1.6] 在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:508)〜[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1419) ~[spring-beans-6.1.6.jar:6.1.6]
在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.1.6.jar:6.1.6]
在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.6.jar:6.1.6]
在 org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.6.jar:6.1.6] 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:962) ~[spring-context-6.1.6.jar:6.1.6]
在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624) ~[spring-context-6.1.6.jar:6.1.6] 在 org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.2.5.jar:3.2.5] 在 org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.2.5.jar:3.2.5] 在 org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.2.5.jar:3.2.5] 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:334) ~[spring-boot-3.2.5.jar:3.2.5] 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1354) ~[spring-boot-3.2.5.jar:3.2.5] 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-3.2.5.jar:3.2.5] 在 com.goblinhorde.goblinhorde.GoblinhordeApplication.main(GoblinhordeApplication.java:11) ~[classes/:na] 在 java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na] 在 java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na] 在 org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:50) ~[spring-boot-devtools-3.2.5.jar:3.2.5]

角色控制器

package com.goblinhorde.goblinhorde.controllers;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.goblinhorde.goblinhorde.models.Characters;
import com.goblinhorde.goblinhorde.models.Store;
import com.goblinhorde.goblinhorde.services.CharacterService;
import com.goblinhorde.goblinhorde.services.StoreService;
import com.goblinhorde.goblinhorde.services.UserService;

@Controller
public class CharacterController {
    
    @Autowired
    private CharacterService cService;
    
    @Autowired
    private UserService uService;
    
    @Autowired
    private StoreService sService;

    @GetMapping("/home")
    public String dashboard(Model viewModel, HttpSession session) {
        Long userId = (Long)session.getAttribute("user_id");
        if(userId == null)
            return"redirect:/";
        
        List<Characters> characters = this.cService.getCharacter();
        viewModel.addAttribute("user", this.uService.findById(userId));
        viewModel.addAttribute("characters", characters);
        return "dashboard.jsp";
    }
    
    // create new Character
    
    @GetMapping("/new")
    private String newCharacter(@ModelAttribute("character") Characters character, HttpSession session, Model viewModel) {
        Long userId = (Long)session.getAttribute("user_id");
        if(userId == null)
            return"redirect:/";
        viewModel.addAttribute("user", this.uService.findById(userId));
        return "newcharacter.jsp";
    }
    
    @PostMapping("/new")
    private String create(@Valid @ModelAttribute("character") Characters character, HttpSession session, BindingResult result, Model viewModel) {
        if(result.hasErrors()) {
            Long userId = (Long)session.getAttribute("user_id");
            viewModel.addAttribute("user", this.uService.findById(userId));
            return "newcharacter.jsp";
        }
            this.cService.create(character);
            return "redirect:/home";
    }
    
    // delete character
    
    @GetMapping("/{id}/delete")
    public String delete(@PathVariable("id") Long id) {
        this.cService.delete(id);
        return "redirect:/home";
    }
    
    // update character name, strength, class
    
    @GetMapping("/{id}")
    public String edit(@PathVariable("id") Long id, HttpSession session, Model viewModel) {
        Long userId = (Long)session.getAttribute("user_id");
        if(userId == null) {
            return "redirect:/";
        } else {
            Characters character = this.cService.findById(id);
            viewModel.addAttribute("character", character);
            viewModel.addAttribute("user", this.uService.findById(userId));
            return "edit.jsp";
        }
    }
    
    @RequestMapping(value = "/{id}", method=RequestMethod.PUT)
    public String update(@Valid @RequestParam("name") String name, @RequestParam("strengthScore") int strengthScore, @RequestParam("charClass") String charClass, @RequestParam("id") Long charId) {
            cService.update(charId, name, charClass, strengthScore);
            return "redirect:/home";
    }
    
    // update character money
    
    @GetMapping("/{id}/coin")
    public String editCoin(@PathVariable("id") Long id, HttpSession session, Model viewModel) {
        Long userId = (Long)session.getAttribute("user_id");
        if(userId == null) {
            return "redirect:/";
        } else {
            Characters character = this.cService.findById(id);
            viewModel.addAttribute("character", character);
            viewModel.addAttribute("user", this.uService.findById(userId));
            return "editcoin.jsp";
        }
    }
    
    @RequestMapping(value = "/{id}/coin", method=RequestMethod.PUT)
    public String updateNew(@Valid @RequestParam("gp") int gp, @RequestParam("sp") int sp, @RequestParam("cp") int cp, @RequestParam("id") Long charId) {
        cService.updateCoin(charId, gp, sp, cp);
        return "redirect:/character/{id}";
    }
    
    // view character
    
    @GetMapping("/character/{id}")
    public String show(@PathVariable("id") Long id, Model viewModel, HttpSession session) {
        Long userId = (Long)session.getAttribute("user_id");
        if(userId == null)
            return"redirect:/";
        
        List<Store> stores = this.sService.getStore();
        viewModel.addAttribute("stores", stores);
        viewModel.addAttribute("character", cService.getOneCharacter(id));
        viewModel.addAttribute("user_id", this.uService.findById(userId));
        return "view.jsp";
        }
    
    // add item to inventory from shop
    
    @GetMapping("/add/{charId}/{itemId}")
    public String add(@PathVariable("charId") Long charId, @PathVariable("itemId") Long itemId, HttpSession session, Model viewModel, String keyword) {
        Long userId = (Long)session.getAttribute("user_id");
        Store characterItems = this.sService.findById(itemId);
        Characters inventories = this.cService.getOneCharacter(charId);
        List<Store> stores = this.sService.getStore();
        String result = this.cService.addItem(characterItems, inventories);
        if(keyword != null) {
            viewModel.addAttribute("stores", sService.findByKeyword(keyword));
        }
        else {
        viewModel.addAttribute("stores", stores);
        }
        viewModel.addAttribute("characters", cService.getOneCharacter(charId));
        viewModel.addAttribute("buyResult", result);
        viewModel.addAttribute("user", this.uService.findById(userId));
        return "redirect:/shop/{charId}";
    }
    
    // remove item from inventory
    
    @GetMapping("/remove/{charId}/{itemId}")
    public String add(@PathVariable("charId") Long charId, @PathVariable("itemId") Long itemId, HttpSession session) {
        Store characterItems = this.sService.findById(itemId);
        Characters inventories = this.cService.getOneCharacter(charId);
        this.cService.removeItem(characterItems, inventories);
        return "redirect:/shop/{charId}";

角色服务

package com.goblinhorde.goblinhorde.services;

import java.util.List;

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

import com.goblinhorde.goblinhorde.models.Characters;
import com.goblinhorde.goblinhorde.models.Store;
import com.goblinhorde.goblinhorde.repositories.CharacterRepository;

@Service
public class CharacterService {
    
    @Autowired
    private CharacterRepository cRepo;
    
    
    public List<Characters> getCharacter() {
        return this.cRepo.findAll();
    }
    
    public Characters findById(Long id) {
        return this.cRepo.findById(id).orElse(null);
    }
    
    public Characters getOneCharacter(Long id) {
        Characters character = this.cRepo.findById(id).orElse(null);
        return character;
    }
    
    // create character
    
    public Characters create(Characters character) {
        int carryCapacity = character.getCarryCapacity();
        character.setCarryCapacity(carryCapacity);
        return this.cRepo.save(character);
    }
    
    // update character
    
    public Characters update(Long id, String name, String charClass, int strengthScore ) {
        Characters updatedCharacter = this.getOneCharacter(id);
        updatedCharacter.setName(name);
        updatedCharacter.setCharClass(charClass);
        updatedCharacter.setStrengthScore(strengthScore);
        int carryCapacity = updatedCharacter.getCarryCapacity();
        updatedCharacter.setCarryCapacity(carryCapacity);
        return this.cRepo.save(updatedCharacter);
    }
    
    // update character money
    
    public void updateCoin(Long id, int gp, int sp, int cp) {
        Characters updatedCharacter = this.getOneCharacter(id);
        updatedCharacter.setGp(gp);
        updatedCharacter.setSp(sp);
        updatedCharacter.setCp(cp);
        cRepo.save(updatedCharacter);
    }
    
    // delete character
    
    public void delete(Long id) {
        this.cRepo.deleteById(id);
    }
    
    //Add item
        public String addItem(Store store, Characters character) {
            if(store.getPriceGP() > character.getGp()) {
                return "Not enough gold.";
            }
            int weight = character.getCarryCapacity() - store.getWeight();
            if(weight <= 0) {
                return "Not enough space.";
            }
            character.updateCarryCapacity(weight);
            int gold = character.getGp() - store.getPriceGP();
            character.setGp(gold);
            List<Store> inventories = character.getInventories();
            inventories.add(store);
            this.cRepo.save(character);
            return "Item purchased.";
        }
        
        // Remove item

        public void removeItem(Store store, Characters character) {
            int weight = character.getCarryCapacity() + store.getWeight();
            int gold = character.getGp() + store.getPriceGP();
            character.updateCarryCapacity(weight);
            character.setGp(gold);
            character.getInventories().remove(store);
            this.cRepo.save(character);
        }
}

角色库

package com.goblinhorde.goblinhorde.repositories;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.goblinhorde.goblinhorde.models.Characters;
import com.goblinhorde.goblinhorde.models.User;

@Repository
public interface CharacterRepository extends CrudRepository<Characters, Long> {
    
    @Override
    List<Characters> findAll();
    List<Characters> findByUser(User user);
    List<Characters> findByStrengthScore(int strengthScore);
    List<Characters> findByName(String name);
    List<Characters> findByCharClass(String charClass);
    Characters findByGp(int gp);
    Characters findBySp(int sp);
    Characters findByCp(int cp);
    Characters findOneById(Long id);
}

** 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.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.goblinhorde.goblinhorde</groupId>
    <artifactId>goblinhorde</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>goblinhorde</name>
    <description>Goblin Horde - TTRPG Shop Generator</description>
    <properties>
        <java.version>22</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.30.2-GA</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mindrot</groupId>
            <artifactId>jbcrypt</artifactId>
            <version>0.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</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-maven-plugin</artifactId>
            <version>3.2.5</version>
        </dependency>
    </dependencies>

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

</project>

不太确定我错过了什么

java spring spring-boot spring-data-jpa crud
1个回答
0
投票

@Repository
注解本身并不强制Spring定义bean,它应该在配置类中显式指定。试试这个:

@EnableJpaRepositories(basePackages = "com.goblinhorde.goblinhorde.repositories")
© www.soinside.com 2019 - 2024. All rights reserved.