使用存储库批注时出现Spring NoSuchBeanDefinitionException

问题描述 投票:0回答:1

我是Spring的新手,添加@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;
		}
	}

}
java spring spring-annotations
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.