-3

While running the application, its throwing an exception of unable to create bean for service class though I have @Service annotation on my Service Interface. I have included the context-component-scan-base-package too but still it is unable to scan my service class package. Even If I place my @Service Annotation on my Service class implementation instead of my Service class interface, it gives the same error. There is a problem in component scanning or with the autowiring of service class. Please help

This is the error that pops up Error

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'medicalController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bhargav.mim.service.MedicalService com.bhargav.mim.rest.web.api.controller.MedicalController.medicalService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bhargav.mim.service.MedicalService] 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:293)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

MedicalController.java Controller class:

package com.bhargav.mim.rest.web.api.controller;

import com.bhargav.mim.entity.Inventory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bhargav.mim.service.MedicalService;

import java.util.List;

@Controller
public class MedicalController {

  @Autowired
  private MedicalService medicalService;

  @RequestMapping(value = "/CompleteInventory", method = {RequestMethod.GET},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public List<Inventory> getAllInventory(){
    return this.medicalService.getAllInventory();
  }

  @RequestMapping("/productName/{productName}")
  @ResponseBody
  public List<Inventory> searchByName(@PathVariable("productName") String productName){
    return medicalService.searchByName(productName);
  }


  @RequestMapping("/productName/{productID}")
  @ResponseBody
  public List<Inventory> searchByName(@PathVariable("productID") int productID){
    return medicalService.searchByID(productID);
  }

  @RequestMapping(value = "/addInventory", method = {RequestMethod.POST},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void addInventory(@RequestParam int productId,
      @RequestParam String productName, @RequestParam int productPrice, @RequestParam int
      productQuantity,
      @RequestParam String productCategory)
      throws Exception {
    Inventory inventory = new Inventory();
     inventory.setProductId(productId);
     inventory.setProductName(productName);
     inventory.setProductCategory(productCategory);
     inventory.setProductPrice(productPrice);
     inventory.setProductQuantity(productQuantity);
    this.medicalService.addInventory(inventory);
  }

  @RequestMapping(value = "/update", method = {RequestMethod.POST},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void updateCustomerRule(@RequestParam String productName, @RequestParam Double productPrice, @RequestParam int
      productQuantity,
      @RequestParam String productCategory, @PathVariable int productId)
      throws Exception {
    Inventory inventory = new Inventory();
    this.medicalService.updateInventory(inventory);
  }

  @RequestMapping(value = "/delete/{productId}", method = {RequestMethod.DELETE},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void deleteInventory(@PathVariable("productId") int productId)
      throws Exception {
    this.medicalService.deleteInventory(productId);
  }

  @RequestMapping("/productNameQueryBased/{productName}")
  @ResponseBody
  public List<Inventory> findByName(@PathVariable("productName") String productName){
    return medicalService.findByName(productName);
  }


  @RequestMapping("/productNameQueryBased/{productID}")
  @ResponseBody
  public List<Inventory> findByName(@PathVariable("productID") int productID){
    return medicalService.findByID(productID);
  }
}


**Service Interface**

package com.bhargav.mim.service;

import com.bhargav.mim.entity.Inventory;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public interface MedicalService {

  List<Inventory> getAllInventory();

  List<Inventory> searchByID(int productID);

  void addInventory(Inventory inventory);

  List<Inventory> searchByName(String productName);

  void updateInventory(Inventory inventory);

  void deleteInventory(int productID);

  List<Inventory> findByID(int productID);

  List<Inventory> findByName(String productName);

}



**Service Class Impl**

package com.bhargav.mim.service.Impl;

import com.bhargav.mim.dao.MedicalRepository;
import com.bhargav.mim.dao.MedicalRepositoryQueryBased;
import com.bhargav.mim.entity.Inventory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.bhargav.mim.service.MedicalService;
import org.springframework.stereotype.Service;

import java.util.List;

public class MedicalServiceImpl implements MedicalService {

  @Autowired
  private MedicalRepository medicalRepository;

  @Autowired
  private MedicalRepositoryQueryBased medicalRepositoryQueryBased;

  public List<Inventory> getAllInventory() {
      return (List<Inventory>) this.medicalRepository.findAll();
  }

  public List<Inventory> searchByID(int productID) {
    return this.medicalRepository.findByProductId(productID);
  }

  public void addInventory(Inventory inventory) {
    this.medicalRepository.save(inventory);

  }

  public List<Inventory> searchByName(String productName) {
    return this.medicalRepository.findByProductName(productName);
  }

  public void updateInventory(Inventory inventory) {
    Inventory savedInventory = this.medicalRepository.findOne(inventory.getProductId());
    BeanUtils.copyProperties(inventory, savedInventory);
    this.medicalRepository.delete(inventory.getProductId());
    this.medicalRepository.save(inventory);
  }

  public void deleteInventory(int productID){
    this.medicalRepository.delete(productID);
  }

  public List<Inventory> findByName(String productName) {
    return this.medicalRepositoryQueryBased.findByProductName(productName);
  }


  public List<Inventory> findByID(int productID) {
    return this.medicalRepositoryQueryBased.findByProductId(productID);
  }
}

**project-context.xml**

<beans
        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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.springframework.org/schema/beans">

    <!-- <context:component-scan base-package="org.product" /> -->
    <context:component-scan
            base-package="com.bhargav.mim">
    </context:component-scan>
    <mvc:annotation-driven />
    <tx:annotation-driven />

    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
        <property value="org.postgresql.Driver" name="driverClassName" />
        <property value="jdbc:postgresql://localhost/testdb" name="url" />
        <property value="testuser" name="username" />
    </bean>
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <!-- THIS IS WHERE THE MODELS ARE -->
        <property name="packagesToScan" value="com.bhargav.mim.entity" />

        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
            </bean>
        </property>
        <property name="jpaProperties">
            <value>
                hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
                hibernate.cache.use_second_level_cache=true
            </value>
        </property>
    </bean>

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

    <jpa:repositories base-package="com.bhargav.mim.dao" />

    <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses">
        <list> <value>org.product.entity.Product</value> </list> </property> <property
        name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
        <prop key="hibernate.hbm2ddl.auto">create-drop</prop> <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.current_session_context_class">thread</prop> </props>
        </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" /> </bean> -->
</beans>

**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_2_5.xsd" version="2.5">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:project-context.xml</param-value>
        <param-value>classpath*:serviceContext.xml</param-value>
        <param-value>classpath*:persistenceContext.xml</param-value>
        <param-value>classpath*:entityContext.xml</param-value>

    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:project-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39

5 Answers5

0

Please use @component annotation on MedicalServiceImpl class

@Component // Add this
public class MedicalServiceImpl implements MedicalService {
   //...
}
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
0

You need to annotate your MedicalServiceImpl class with @component or @service and remove annotation from interface

You dont need to annotate your interface

public interface MedicalService {

  List<Inventory> getAllInventory();

  List<Inventory> searchByID(int productID);

  void addInventory(Inventory inventory);

  List<Inventory> searchByName(String productName);

  void updateInventory(Inventory inventory);

  void deleteInventory(int productID);

  List<Inventory> findByID(int productID);

  List<Inventory> findByName(String productName);

}
Vishnu T S
  • 3,476
  • 2
  • 23
  • 39
0

I think you are missing context:annotation-config in spring-servlet.xml file. Just add that tag before component scan tag. It should work.

Also remove the @Service annotation from interface and add that annotation to implementation class. Let me know in case if it doesn't work.

Rohit
  • 146
  • 1
  • 5
  • Thank you for your answer. But it still shows the same problem. – AISHWARY VARSHNEY Dec 11 '17 at 10:10
  • Can you provide the path of ur project-context.xml in full path in web.xml. In web.xml you have used contextconfiglocation parameter which has path of configuration file. Can you change the path to /WEB-INF/project-context.xml. – Rohit Dec 11 '17 at 10:27
0

There are a number of answers here. All of them will work. In this case, what you have is a service.

  • We can classify it more than just a component (@Component)
  • It is not a repository (@Repository), it doesn't interact directly with the data layer.
  • It's clearly not a controller (@Controller).

Please read more here to understand them: What's the difference between @Component, @Repository & @Service annotations in Spring?

@Service // Add this
public class MedicalServiceImpl implements MedicalService {
   //...
}

You can also remove your annotation from your interface. Your interface simply allows you to define the "Shape" of your bean. In and of itself, it's not doing any actions. It allows another developer to come along and create a new implementation, and remove the old one. This allows them to adhere to the interface, ensuring that wherever that interface is defined, the application logic will continue to work.

Brian
  • 4,921
  • 3
  • 20
  • 29
0

simply update your service implementation as below

@Service
public class MedicalServiceImpl implements MedicalService {

  @Autowired
  private MedicalRepository medicalRepository;

  @Autowired
  private MedicalRepositoryQueryBased medicalRepositoryQueryBased;

  public List<Inventory> getAllInventory() {
      return (List<Inventory>) this.medicalRepository.findAll();
  }

  public List<Inventory> searchByID(int productID) {
    return this.medicalRepository.findByProductId(productID);
  }

  public void addInventory(Inventory inventory) {
    this.medicalRepository.save(inventory);

  }

  public List<Inventory> searchByName(String productName) {
    return this.medicalRepository.findByProductName(productName);
  }

  public void updateInventory(Inventory inventory) {
    Inventory savedInventory = this.medicalRepository.findOne(inventory.getProductId());
    BeanUtils.copyProperties(inventory, savedInventory);
    this.medicalRepository.delete(inventory.getProductId());
    this.medicalRepository.save(inventory);
  }

  public void deleteInventory(int productID){
    this.medicalRepository.delete(productID);
  }

  public List<Inventory> findByName(String productName) {
    return this.medicalRepositoryQueryBased.findByProductName(productName);
  }


  public List<Inventory> findByID(int productID) {
    return this.medicalRepositoryQueryBased.findByProductId(productID);
  }
}

and remove @Service annotation from your interface.

Saurav
  • 392
  • 4
  • 4