【问题标题】:Couldn't autowire field in @RestController无法在 @RestController 中自动装配字段
【发布时间】:2017-08-08 01:50:27
【问题描述】:

我遇到了问题。而且我研究了很多相同的主题,但我无法解决问题。 我有 SpringBoot 应用程序。我想开发 RestController 类。以及它的外观:

@RequestMapping("achievement/")
@RestController
public class AchievementController {

@Autowired
private AchievementManager manager;

@RequestMapping(value = "{id}", method = RequestMethod.GET)
public Achievement showAchievement(@PathVariable("id") Long id) throws DBException {
    return manager.getAchievementById(id);
}

@RequestMapping(value = "/", consumes = "application/json", method = RequestMethod.POST)
public Achievement createAchievement(@RequestBody Achievement achievement) throws DBException {
    return manager.createAchievementAndReturn(achievement);
}

@RequestMapping(value = "{id}", consumes = "application/json", method = RequestMethod.PUT)
public Achievement changeAchievement(@PathVariable("id") Long id, @RequestBody Achievement achievement) throws DBException {
    return manager.saveChangesAndReturn(id, achievement);
}
}

我在使用 @Autowire 管理器字段时遇到了问题

Exception encountered during context initialization - cancelling
refresh attempt:org.springframework.beans.factory.
BeanCreationException: 
Error creating bean with name 'achievementController': Injection of 
autowired dependencies failed; nested exception is 
org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private  
com.rpglife.data.managers.AchievementManager  
com.rpglife.controller.AchievementController.manager; nested exception   
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No 
qualifying bean of type [com.rpglife.data.managers.AchievementManager] 
found for dependency: expected at least 1 bean which qualifies as     
autowire candidate for this dependency. Dependency annotations: {
@org.springframework.beans.factory.annotation.Autowired(required=true)}
.
.
.
Caused by: org.springframework.beans.factory.
NoSuchBeanDefinitionException: No qualifying bean of type  
[com.rpglife.data.managers.AchievementManager] found for dependency:  
expected at least 1 bean which qualifies as autowire candidate for this   
dependency. Dependency annotations:{
@org.springframework.beans.factory.annotation.Autowired(required=true)}

我的 AchievmentManager 类:

@SuppressWarnings("unchecked")
public class AchievementManager {

private final Class thisClass = Achievement.class;
private BaseDAO dao;

public AchievementManager(BaseDAO dao) {
    this.dao = dao;
}

public Achievement getAchievementById(Long id) {
    return (Achievement) dao.getItem(thisClass, id);
}

public Achievement createAchievementAndReturn(Achievement achievement) {
    dao.createItem(achievement);
    return getAchievementById(achievement.getId());
}

public Achievement saveChangesAndReturn(Long id, Achievement achievement) {
    return dao.updateItem(thisClass, id, achievement);
}
}

Spring xml 在这里:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans       
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean name="manager" class="com.rpglife.data.managers.AchievementManager" >
    <constructor-arg name="dao" ref="dao"/>
</bean>

<bean name="dao" class="com.rpglife.data.BaseDAO" >
    <constructor-arg name="sessionFactory" ref="sessionFactory"/>
</bean>

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="hibernate.cfg.xml"/>
</bean>

<context:component-scan base-package="com.rpglife.data"/>

</beans>

主类:

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

这里是我的项目结构(如果需要,我也可以附加资源): enter image description here

我试图弄清楚的:

  1. 我尝试使用@Qualyfier("manager")
  2. 尝试使用 @ComponentScan(basePackages = {"com.rpglife"}) 和 @SpringBootApplication(scanBasePackages={"com.rpglife"}) (但主要 类留在 com.rpglife 中。其他包也在这里,我确定 这没用)

我不知道出了什么问题... 如果您能给我一些答案和建议,我将非常感激。希望你有美好的一天!)

更新: 我认为我的 spring.xml 可能有问题。如果它不起作用并且无法定义bean怎么办?如何检查...

更新: 添加@时出错

Exception encountered during context initialization - cancelling 
refresh attempt: 
org.springframework.beans.factory.BeanCreationException: Error creating 
bean with name 'achievementController': Injection of autowired 
dependencies failed; nested exception is 
org.springframework.beans.factory.BeanCreationException: Could not 
autowire field: private com.rpglife.data.managers.AchievementManager 
com.rpglife.controller.AchievementController.manager; nested exception 
is org.springframework.beans.factory.BeanCreationException: Error 
creating bean with name 'achievementManager' defined in file 
[/Users/eignatik/IdeaProjects/LifeRPG/be/target
/classes/com/rpglife/data/managers/AchievementManager.class]: 
Instantiation of bean failed; nested exception is 
org.springframework.beans.BeanInstantiationException: Failed to 
instantiate [com.rpglife.data.managers.AchievementManager]: No default 
constructor found; nested exception is java.lang.NoSuchMethodException: 
com.rpglife.data.managers.AchievementManager.<init>()

【问题讨论】:

  • 在附件基础包中是 com.rpglife ,你在 @ComponentScan org.rpglife 中将 basepackage 更改为 com.rpglife
  • 你的 SpringBootApplication (Main.class) 在哪个包中? @SpringBootApplication 会自动扫描 spring boot 主包下的所有包/类(在您的情况下为 com.rpglife)。所以它应该捡起来。为什么在 Spring Boot 应用程序中使用 Spring xml?为什么不用@Component / @Service 注释所有类?
  • @hichamabdedaime aw,这里只是错字,我现在写的例子)
  • @ddewaele package is com.rpglife 我附上了我的项目结构的屏幕i.stack.imgur.com/p1Zvj.png
  • 使用 Autowired 和 Qualyfier("sessionFactory") 尝试在成就管理器和 BaseDAO 以及您的 sessionFactory 中使用 @component

标签: java spring spring-boot


【解决方案1】:

您正在混合使用 Spring Boot 和基于 XML 的应用程序上下文。

默认情况下,Spring Boot 不会加载您的应用程序上下文 xml 文件。 (Spring boot 大力推广非基于 xml 的上下文)

你有两个选择:

  1. 不要使用 XML,对类的所有内容进行注释。所有嵌套在 @SpringBootApplication 包中的 Spring 注释类都将被扫描。恕我直言,这就是 Spring Boot 的使用方式。
  2. 如果您真的想继续使用 xml,请勾选此项http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-importing-xml-configuration

【讨论】:

  • 是的,谢谢,你说得对。将来我们不想使用 SpringBoot。谢谢,我试试第二种方法...
  • 我强烈推荐使用 Spring Boot 并转储 xml。尤其是在新项目上。如果你喜欢这个答案,请接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 2016-02-23
相关资源
最近更新 更多