Spring NoSuchBeanDefinitionException при использовании аннотации репозитория - PullRequest
1 голос
/ 24 февраля 2020

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>WebStore</display-name>
  <servlet>
  	<servlet-name>WebServlet</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
				/WEB-INF/config/servlet-config.xml
			</param-value>
		</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>WebServlet</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
</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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		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">

	<mvc:annotation-driven enable-matrix-variables="true"></mvc:annotation-driven>
	
	<context:component-scan base-package="com.packt"/>

	 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
	 p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
	 
	 

</beans>

Я новичок в весне, и я получаю ошибки при добавлении @Repository аннотации

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.packt.webstore.domain.repository.ProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. 
    Dependency annotation {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value="ProductRepository")}

Код приведен ниже:

package com.packt.webstore.controller;

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

import com.packt.webstore.domain.repository.ProductRepository;

@Controller
@ComponentScan(basePackages= {"com.packt.webstore.domain.repository.impl","com.packt.webstore.domain.repository"})
public class ProductController {

    @Autowired
    @Qualifier("ProductRepository")
    private ProductRepository productRepository;


    @RequestMapping("/products")
    public String list(Model model) {
        model.addAttribute("products",productRepository.getAllProducts());
        return "products";
    }
}



package com.packt.webstore.domain.repository.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;

@Component
@Repository
public class ProductRepositoryImpl implements ProductRepository {


    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private void setDataSource(DataSource dataSource) {
        this.jdbcTemplate=new NamedParameterJdbcTemplate(dataSource);
    }


    @Override
    public List<Product> getAllProducts() {
        Map<String, Object>params=new HashMap<String,Object>();
        List<Product>result=jdbcTemplate.query("SELECT * FROM PRODUCTS", params, new ProductMapper());
        return result;
    }

    private static final class ProductMapper implements org.springframework.jdbc.core.RowMapper<Product> {
        public Product mapRow(ResultSet rs,int rownum) throws SQLException{
            Product product=new Product();
            product.setName(rs.getString("name"));
            return product;
        }
    }

}

1 Ответ

3 голосов
/ 24 февраля 2020

Либо оставьте @Component или @Repository в ProductRepositoryImpl. И то, и другое невозможно.

В дополнение к этому, сохраняйте верблюд в таком виде @Qualifier("productRepository").

Удалите @ComponentScan из контроллера. Это должно быть в Java Config.

Пример Java - Based Config:

@Configuration
@ComponentScan(basePackages = "com.packt")
public class Config {

}

Если используется XML -Big Config, выполните следующие действия:

Обновление applicationContext.xml или любое servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring Application Context File -->
<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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- Added support for component scanning -->
    <context:component-scan base-package="com.packt" />
</beans>

Если это не работает, проверьте файлы пользовательского сервлета XML или applicationContext.xml с web.xml на наличие ошибок конфигурации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...