我正在创建Rest + Spring + Jpa演示,一切正常,但是当我要注入CartRepository的依赖项时,扩展JpaRepository,那时它会向我显示以下错误,
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cartServices': Unsatisfied dependency expressed through field 'cartRepository': No qualifying bean of type [com.xptraining.repository.CartRepository] found for dependency [com.xptraining.repository.CartRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xptraining.repository.CartRepository] found for dependency [com.xptraining.repository.CartRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
My Bean Class -------------->>>
package com.xptraining.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "cart")
public class Cart {
@Id
@GeneratedValue
@Column(name = "cart_id")
private long cartId;
@Column(name = "sku_id")
private String skuId;
@Column(name = "representative_id")
private String representativeId;
@Column(name = "quantity")
private int quantity;
@Column(name = "prize")
private int prize;
public long getCartId() {
return cartId;
}
public void setCartId(long cartId) {
this.cartId = cartId;
}
public String getSkuId() {
return skuId;
}
public void setSkuId(String skuId) {
this.skuId = skuId;
}
public String getRepresentativeId() {
return representativeId;
}
public void setRepresentativeId(String representativeId) {
this.representativeId = representativeId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrize() {
return prize;
}
public void setPrize(int prize) {
this.prize = prize;
}
}
My Controller-------->>>
@Controller
@RequestMapping("/cart")
public class CartController {
@Autowired
CartService cartServices;
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Status addCart(@RequestBody Cart cart) {
try {
cartServices.addCart(cart);
return new Status(1, "Cart added Successfully !");
} catch (Exception e) {
// e.printStackTrace();
return new Status(0, e.toString());
}
}
@RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
public @ResponseBody Status deleteCart(@PathVariable("id") long id) {
try {
cartServices.deleteCart(id);
return new Status(1, "Cart deleted Successfully !");
} catch (Exception e) {
return new Status(0, "Record is not Found ");
}
}
my service Impl class--------------->>>
@Transactional
public class CartServiceImpl implements CartService {
@Inject
CartRepository cartRepository;
@Override
public Cart addCart(Cart cart) throws Exception {
// TODO Auto-generated method stub
return cartRepository.save(cart);
}
@Override
public void deleteCart(long id) throws Exception {
// TODO Auto-generated method stub
cartRepository.delete(id);
}
}
My Repository------------------->>>>
package com.xptraining.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.xptraining.model.Cart;
@Repository
@Transactional
public interface CartRepository extends JpaRepository<Cart, Long>
{
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>xptraining</display-name>
<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/rest.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
rest.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"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="com.xptraining.controller" />
<jpa:repositories base-package="com.xptraining.repository"></jpa:repositories>
<!-- <jpa:repositories base-package="com.xptraining.repository"
entity-manager-factory-ref="cartRepository"
transaction-manager-ref="transactionManager"/> -->
<mvc:annotation-driven />
<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/training" />
<property name="username" value="root" />
<property name="password" value="xpointers" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.xptraining.model.Product</value>
<value>com.xptraining.model.Specialties</value>
<value>com.xptraining.model.Representative</value>
<value>com.xptraining.model.Cart</value>
<value>com.xptraining.model.Sku</value>
<value>com.xptraining.model.Order</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataDao" class="com.xptraining.dal.impl.DataDaoImpl"></bean>
<bean id="dataServices" class="com.xptraining.services.impl.DataServicesImpl"></bean>
<bean id="specialtiesDao" class="com.xptraining.dal.impl.SpecialtiesDaoImpl"></bean>
<bean id="specialtiesServices" class="com.xptraining.services.impl.SpecialtiesServicesImpl"></bean>
<bean id="representativeDao" class="com.xptraining.dal.impl.RepresentativeDaoImpl"></bean>
<bean id="representativeService" class="com.xptraining.services.impl.RepresentativeServiceImpl"></bean>
<bean id="skuDao" class="com.xptraining.dal.impl.SkuDaoImpl"></bean>
<bean id="skuServices" class="com.xptraining.services.impl.SkuervicesImpl"></bean>
<bean id="cartDao" class="com.xptraining.dal.impl.CartDaoImpl"></bean>
<bean id="cartServices" class="com.xptraining.services.impl.CartServiceImpl"></bean>
<bean id="orderDao" class="com.xptraining.dal.impl.OrderDaoImpl"></bean>
<bean id="orderServices" class="com.xptraining.services.impl.OrderServicesImpl"></bean>
</beans>
CartDaoImpl -----------------&GT;&GT;&GT;&GT;&GT;&GT;
package com.xptraining.dal.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.xptraining.dal.CartDao;
import com.xptraining.model.Cart;
/**
* Cart DAL Implementation Class
*
* @author Harshad Kenjale
*
*/
public class CartDaoImpl implements CartDao {
@Autowired
SessionFactory sessionFactory;
Session session = null;
Transaction tx = null;
/**
* Get All Cart
*
* @throws Exception
* @return All Cart List
*/
@SuppressWarnings("unchecked")
@Override
public List<Cart> getCartList() throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<Cart> cartList = session.createCriteria(Cart.class).list();
tx.commit();
session.close();
return cartList;
}
/**
* Add Cart
*
* @param Cart
* @throws Exception
* @return boolean TRUE or FALSE
*/
@Override
public boolean addCart(Cart cart) throws Exception {
// TODO Auto-generated method stub
session = sessionFactory.openSession();
tx = session.beginTransaction();
session.save(cart);
tx.commit();
session.close();
return false;
}
/**
* Delete Cart
*
* @param id
* Cart id
* @throws Exception
* @return boolean TRUE or FALSE
*/
@Override
public boolean deleteCart(long id) throws Exception {
session = sessionFactory.openSession();
Object o = session.load(Cart.class, id);
tx = session.getTransaction();
session.beginTransaction();
session.delete(o);
tx.commit();
return false;
}
/**
* Update Cart
*
* @param Cart
* @throws Exception
* @return boolean TRUE or FALSE
*/
@Override
public boolean updateCart(Cart cart) throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
session.saveOrUpdate(cart);
tx.commit();
session.close();
return false;
}
}
答案 0 :(得分:2)
问题在于:
您正试图将sessionFactory
传递给entity-manager-factory-ref
。这导致错误:
Error creating bean with name '(inner bean)#542901d0': Unsatisfied dependency expressed through method 'createSharedEntityManager' parameter 0: Could not convert argument value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]: Failed to convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]: no matching editors or conversion strategy found
要解决此问题,请更改以下配置文件:
添加此bean声明:
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.xptraining.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
然后将jpa存储库标记更改为指向此bean:
<jpa:repositories base-package="com.xptraining.repository"
entity-manager-factory-ref="entityManagerFactoryBean"
transaction-manager-ref="txManager"/>
这可以解决您的问题。
要解决Hibernate验证程序问题,请将其添加到您的pom.xml文件中:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.0.Final</version>
</dependency>
您可以使用以下格式启用XML事务:
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
答案 1 :(得分:0)
我相信你在rest.xml文件中缺少jpa:repositories
标记。这有助于查找Spring Data存储库。
假设您的存储库位于包com.acme.repositories
中,则标记看起来像
<jpa:repositories base-package="com.acme.repositories" />
有关详细信息,请参阅ScheduledThreadPoolExecutor。
答案 2 :(得分:0)
使用此配置:
<jpa:repositories base-package="com.xptraining.repository"
entity-manager-factory-ref="sessionFactory"
transaction-manager-ref="txManager"/>
仔细查看sessionFactory
和txManager
。
答案 3 :(得分:0)
您当前的项目结构无效。它应该是
src
+- main
+- java
+- com
+- xptraining
+- config
+- controller
+- dal
+- model
+- repository
+- services
+- resources
+- webapp
+- META-INF
+- WEB-INF
请更正您的项目结构并重新构建。