gpt4 book ai didi

java - Spring 问题 : Error creating beans and Injection of autowired dependencies failed

转载 作者:行者123 更新时间:2023-12-03 11:18:54 25 4
gpt4 key购买 nike

所以我正在尝试学习 spring 并且我已经阅读了很多教程并尝试从我在闪存驱动器中的项目中复制一些代码。

我已经设置了 tomcat 并且它可以正常工作,但是我在这里仍然遇到一些问题。
问题是我通常可以毫无问题地从浏览器访问 Controller 的操作,但是当我开始添加注释和 ContextLoaderListener 时,它一直给我 404 状态。我不知道我做了什么,但是通过调整周围的一些东西,我的浏览器至少会尝试再次访问 Controller 。但是抛出了一个巨大的错误日志,我将在本文末尾分享。

这些是我的依赖项:

  • junit 4.12
  • spring-webmvc 4.1.6.RELEASE
  • spring-context 4.1.6.RELEASE
  • spring-web 4.1.6.RELEASE
  • spring-beans 4.1.6.RELEASE
  • spring-data-jpa 1.8.0.RELEASE
  • spring-jdbc 4.1.6.RELEASE
  • mysql-connector-java 5.1.35
  • jstl 1.2
  • javax.servlet-api 3.1.0 (scope provided)
  • javax.servlet.jsp-api 3.1.0 (scope provided)
  • jackson-databind 2.5.4
  • jackson-core 2.5.4
  • jackson-core-asl 1.9.13
  • jackson-datatype-hibernate4 2.5.4
  • hibernate-annotations 3.5.6-Final
  • hibernate-commons-annotations 3.2.0.Final
  • hibernate-entitymanager 4.3.10.Final
  • jsondoc-core 1.1.15
  • jsondoc-springmvc 1.1.15
  • jsondoc-ui-webjar 1.1.15
  • commons-logging 1.2
  • commons-logging-api 1.1
  • commons-dbcp 1.4


我的构建插件是:

  • maven-compiler-plugin 3.1 (source and target 1.8)
  • maven-war-plugin 2.4


我的 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring Web MVC Application</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:WEB-INF/application-context.xml
classpath*:WEB-INF/persistence-context.xml
</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>

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

<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.ve.main.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

<bean id="documentationController" class="org.jsondoc.springmvc.controller.JSONDocController">
<constructor-arg name="version" value="1.0"/>
<constructor-arg name="basePath" value="http://localhost:4848/spring2"/>
<constructor-arg name="packages">
<list>
<value>com.ve</value>
</list>
</constructor-arg>
</bean>

我的 application-context.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

我的persistence-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/my_database" />
<property name="username" value="my_actual_db_user" />
<property name="password" value="my_actual_db_password" />
</bean>

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<jpa:repositories base-package="com.ve" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />

仅供引用,我还将引用我的类(class)代码和我的项目结构

股票 Controller
package com.ve.common.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ve.common.service.StockService;

@Controller
@RequestMapping("/stock")
public class StockController {

@Autowired
private StockService stockService;

public StockController(){}

@RequestMapping(value="/list", method = RequestMethod.GET, produces={"application/json","application/xml"})
@ResponseBody
public String findAllStocks(){
return "stocks";
}
}

股票服务
package com.ve.common.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ve.common.model.Stock;
import com.ve.common.repo.StockRepository;

@Service
public class StockService {

@Autowired
private StockRepository stockRepository;

StockService(){}

List<Stock> findStock(){
return (List<Stock>) stockRepository.findAll();
}
}

StockRepository
package com.ve.common.repo;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ve.common.model.Stock;

@Repository
public interface StockRepository extends CrudRepository<Stock, Integer> {

List<Stock> findByStockName(String stockName);

Stock findByStockId(Integer stockId);
}

我的模型是一个基本的实体类,它实现了 Serializable(由 JPA 工具创建)。
现在这是我的项目结构,很抱歉我不能把图像变小(我现在很忙)。
Project Structure

这是我访问“ http://localhost:4848/spring2/api/welcome/hi”或“ http://localhost:4848/spring2/api/stock/list”时在浏览器中遇到的巨大错误的引用

HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception

type Exception report

message Servlet.init() for servlet mvc-dispatcher threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)

root cause

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ve.common.service.StockService com.ve.common.controller.StockController.stockService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)

root cause

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ve.common.service.StockService com.ve.common.controller.StockController.stockService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)

root cause

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)



对于过多的代码阻塞和引用,我深表歉意,但我认为我提供的信息越多,我能得到的帮助就越好。我预先感谢任何可以帮助我的人。

最佳答案

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService]



错误本身表明 SpringContainer 找不到名称为 的 bean StockService .所以要么你在 applicationContext.xml 中创建 bean使用 @Bean 文件或声明 bean注解。

@Autowired :这个注解允许你不用在 applicationContext.xml 中显式声明你的 bean .但是您必须使用 @Bean 创建要 Autowiring 的类的 bean注释和添加 <context:conponent-scan>XML要知道正在使用 @Bean 创建 bean注解。

声明 Bean:声明 bean 用 @Bean 注释方法注释就像
@Configuration
public class AppConfig {
@Bean
public StockService stockService() {
return new StockServiceImpl();
}
}

这相当于在 applicationContext.xml 中声明 bean
<beans>
<bean name="stockService" class="com.ve.common.service.StockServiceImpl"/>
</beans>



如果您想使用 @Autowired bean 类中的注释必须首先使用以下配置在 spring 中启用注释:
<context:annotation-config />

或者
<bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

更多信息:
  • Spring beans autowiring
  • @Bean - Declaring a bean

  • 希望这对你有帮助。

    关于java - Spring 问题 : Error creating beans and Injection of autowired dependencies failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992230/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com