it-roy-ru.com

Неудовлетворенная зависимость, выраженная через поле 'service': нет подходящего компонента типа

Привет, ребята, мне может помочь любое тело Я создаю новый проект, используя spring mvc и hibernate Это мой репозиторий

package com.cs545.ecom.repository;

import Java.util.List;

import com.cs545.ecom.domain.Product;

public interface ProductDAO {
    List<Product> getAllProducts();

    Product getProductById(int id);

    Product getProductByName(String name);

    Product addNewProduct(Product product);

    Product updateProduct(int productId, Product product);

}

и это реализация

package com.cs545.ecom.repository.impl;

import Java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Repository;

import com.cs545.ecom.domain.Product;
import com.cs545.ecom.repository.ProductDAO;

@Repository
public class ProductDAOimpl implements ProductDAO{

    SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
    public List<Product> getAllProducts() {
        // TODO Auto-generated method stub
        return null;
    }

    public Product getProductById(int id) {
        // TODO Auto-generated method stub
        return null;
    }

    public Product getProductByName(String name) {
        // TODO Auto-generated method stub
        return null;
    }

    public Product addNewProduct(Product product) {
        Product productSaved=new Product();
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        productSaved=(Product)session.save(product);
        session.getTransaction().commit();
        session.close();
        return productSaved;
    }

    public Product updateProduct(int productId, Product product) {
        // TODO Auto-generated method stub
        return null;
    }

}

также это интерфейс сервиса

package com.cs545.ecom.service;

import com.cs545.ecom.domain.Product;

public interface ProductService {
    Product addNewProduct(Product product);
}

и это реализация сервиса

package com.cs545.ecom.service.impl;



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

import com.cs545.ecom.domain.Product;
import com.cs545.ecom.repository.ProductDAO;
import com.cs545.ecom.service.ProductService;
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDAO repository;

    public Product addNewProduct(Product product) {
        return repository.addNewProduct(product);
    }

}

это контроллер

package com.cs545.ecom.controller;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cs545.ecom.domain.Category;
import com.cs545.ecom.domain.Product;
import com.cs545.ecom.repository.ProductDAO;
import com.cs545.ecom.service.ProductService;

@Controller
public class ProductController {
    @Autowired
    public ProductService service;

    @RequestMapping("/")
    public String start() {
        return "UI/jsp/product";
    }
    @RequestMapping("/addproduct")
    public String addNewProduct(Model model){
    //  Product product=service.addNewProduct(new Product("Apple iphone", "gfgfg", "Amazing Iphone ", new Category()));
        //Product product=new Product("Apple iphone", "gfgfg", "Amazing Iphone ", new Category());

        //model.addAttribute("product",product);
        return "UI/jsp/product";
    }
}

когда я запускаю программу, я получаю эту ошибку

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


type Exception report

message Servlet.init() for servlet Dispatcher Servlet threw exception

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

exception
javax.servlet.ServletException: Servlet.init() for servlet Dispatcher Servlet threw exception
    org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:502)
    org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:79)
    org.Apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.Java:616)
    org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:528)
    org.Apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.Java:1099)
    org.Apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.Java:672)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.Java:1520)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.Java:1476)
    Java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    Java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
    Java.lang.Thread.run(Unknown Source)


root cause
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'service': No qualifying bean of type [com.cs545.ecom.service.ProductService] found for dependency [com.cs545.ecom.service.ProductService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cs545.ecom.service.ProductService] found for dependency [com.cs545.ecom.service.ProductService]: 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:569)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.Java:88)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:349)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1214)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:543)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:775)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:861)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.Java:668)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.Java:634)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.Java:682)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.Java:553)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.Java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.Java:136)
    javax.servlet.GenericServlet.init(GenericServlet.Java:158)
    org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:502)
    org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:79)
    org.Apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.Java:616)
    org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:528)
    org.Apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.Java:1099)
    org.Apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.Java:672)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.Java:1520)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.Java:1476)
    Java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    Java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
    Java.lang.Thread.run(Unknown Source)


root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cs545.ecom.service.ProductService] found for dependency [com.cs545.ecom.service.ProductService]: 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:1403)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:1056)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:1018)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:566)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.Java:88)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:349)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1214)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:543)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:775)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:861)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.Java:668)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.Java:634)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.Java:682)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.Java:553)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.Java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.Java:136)
    javax.servlet.GenericServlet.init(GenericServlet.Java:158)
    org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:502)
    org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:79)
    org.Apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.Java:616)
    org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:528)
    org.Apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.Java:1099)
    org.Apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.Java:672)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.Java:1520)
    org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.Java:1476)
    Java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    Java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
    Java.lang.Thread.run(Unknown Source)

это мой файл web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--init-param is not needed when followed default naming convention for configuration file "DefaultServlet-servlet.xml"-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/dispatcher-config.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Dispatcher Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

и это весенняя конфигурация

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    ">
  <mvc:annotation-driven/>
  <mvc:resources mapping="/resources/**" location="/resources/"/>
  <context:component-scan base-package="com.cs545.ecom.controller"/>

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp"/>
  </bean>
  <bean id= "messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>

</beans>

также это спящий режим

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">111111</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3338/waaProject</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.cs545.ecom.domain.Product"></mapping>
    </session-factory>
</hibernate-configuration>

Кто-нибудь может мне помочь?

3
Hamada Ibrahim

В настройке компонентного сканирования необходимо включить com.cs545.ecom.service  
Так что вы должны иметь

<context:component-scan base-package="com.cs545.ecom.controller, com.cs545.ecom.service"/>
5
Lê Thọ

Измените context:component-scan в web.xml, как показано ниже

  <context:component-scan base-package="com.cs545.ecom"/>

Spring зарегистрирует все bean-компоненты, определенные внутри данного пакета. В вашем случае только bean-компонент контроллера будет зарегистрирован, а bean-компоненты службы - нет.

0
vipin cp

Как уже упоминалось в других ответах, вы должны настроить сканирование classpath для вашего компонента, чтобы быть уверенным, что он может быть автоматически подключен к другому компоненту.

Помимо этого, эта ошибка может быть вызвана рядом других проблем. Основная причина этого заключается в том, что контейнер IOC не инициализировал компонент типа SomeType, когда среда выполнения пытается автоматически передать этот тип компонента в какой-то другой класс.

Эта статья обобщает возможные ошибки, которые могут вызвать это.

0
Supun Wijerathne