2013-03-22 2 views
5

Я новичок в данных весны. Я хочу попробовать использовать данные весны, не используя @autowired над репозиториями. Я просто хочу направить инъекции Хранилища через xml, потому что я не могу получить экземпляр репозитория в моем классе реализации из xml, причина использования конфигурации на основе xml - это мой предыдущий уровень сервиса и контроллер не поддерживают функцию аннотации, поэтому я должны просто манипулировать дао слой с помощью пружинных данных это моя конфигурация XMLвводят репозитории в класс реализации без использования @autowired в данных весны с помощью 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:jdbc="http://www.springframework.org/schema/jdbc" 
      xmlns:context="http://www.springframework.org/schema/context" 
      xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
      xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 


      <context:component-scan base-package="com.nousinfo.tutorial" /> 
      <!-- Database --> 
      <bean id="datasource" 
       class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
       <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
       <property name="url" value="jdbc:mysql://192.168.25.30:3306/employee" /> 
       <property name="username" value="***" /> 
       <property name="password" value="*****" /> 
      </bean> 

      <!-- Entity Manager --> 
      <bean id="entityManagerFactory" 
       class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
       <property name="dataSource" ref="datasource" /> 
       <property name="persistenceUnitName" value="EmployeeApp" /> 
      </bean> 

      <!-- Transaction Manager --> 
      <beanid="transactionManager"                    class="org.springframework.orm.jpa.JpaTransactionManager"> 
       <property name="entityManagerFactory" ref="entityManagerFactory" /> 
      </bean> 

    <!--- here i having problem on injecting the bean of employeeRepositories----> 
      <bean id="employeeDaoImpl" class="com.nousinfo.tutorial.repository.impl.EmployeeDAOImpl"> 
       <property name="employeeRepository" ref="employeeRepository" /> 
      </bean> 
    <bean id="employeeRepositories" class="com.nousinfo.tutorial.dao.EmployeeRepositories"/> 


      <!-- Jpa Repositories --> 
      <jpa:repositories base-package="com.nousinfo.tutorial.dao"></jpa:repositories> 

    </beans> 

это мой persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence" 
version="1.0"> 
<persistence-unit name="EmployeeApp" transaction-type="RESOURCE_LOCAL"> 
    <provider>org.hibernate.ejb.HibernatePersistence</provider> 
     <class>com.nousinfo.tutorial.model.Department</class> 
    <properties> 
     <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> 
     <property name="hibernate.hbm2ddl.auto" value="update" /> 
     <property name="hibernate.show_sql" value="true" /> 
    </properties> 
</persistence-unit> 

Это мой Хранилища Сотрудник

public interface EmployeeRepositories extends JpaRepository<Employee, Long> { 
    public List<Employee> findByFirstName(String name); 

    @Query("FROM Employee emp WHERE emp.firstName = :firstname or emp.lastName = :lastname") 
    List<Employee> getEmployeesByName(@Param("lastname") String lastname, 
      @Param("firstname") String firstname); 

    List<Employee> findByLastNameOrderByFirstNameAsc(String lastname); 

    List<Employee> findByLastNameOrderByFirstNameDesc(String lastname); 

    List<Employee> findByDepartmentId(String departmentId); 

}

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

public class EmployeeDAOImpl { 

EmployeeRepositories employeeRepositories ; 

public void setEmployeeRepositories (EmployeeRepositories employeeRepositories) { 
    this.employeeRepositories = employeeRepositories ; 
} 

public List<Employee> getAllEmployees() { 
    return employeeRepositories.findAll(); 
} 

таким образом им вызов метода для тестирования

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("MyBean.xml"); 
     EmployeeDAOImpl daOImpl=(EmployeeDAOImpl)applicationContext.getBean("employeeDaoImpl"); 
daOImpl.getAllEmployees(); 

Исключение приходит из-за неправильного отображения поэтому, пожалуйста, предоставить мне правильное отображение я буду благодарен u

вот мое исключение

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDaoImpl' defined in class path resource [mybeans.xml]: Cannot resolve reference to bean 'employeeRepositories' while setting bean property 'employeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepositories' defined in class path resource [mybeans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nousinfo.tutorial.dao.EmployeeRepository]: Specified class is an interface 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1317) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1076) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:574) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) 
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) 
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) 
    at com.nousinfo.tutorial.common.basemodel.MainTest.main(MainTest.java:13) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepositories' defined in class path resource [mybeans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nousinfo.tutorial.dao.EmployeeRepository]: Specified class is an interface 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:955) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:901) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) 
    ... 15 more 
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nousinfo.tutorial.dao.EmployeeRepository]: Specified class is an interface 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:52) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:948) 
    ... 23 more 
+0

получил какого-либо Результаты? –

+0

@MichailNikolaev Я попробовал способ, который сказал, но его не удалось ввести в хранилища im, вставив мое исключение, пожалуйста, пройдите это и помогите мне в этом – user1527637

+0

проверить обновленный ответ –

ответ

2

Удалить

<bean id="employeeRepositories" class="com.nousinfo.tutorial.repository.EmployeeRepositories"/> 

и использование:

 <bean id="employeeDaoImpl" class="com.nousinfo.tutorial.repository.impl.EmployeeDAOImpl"> 
      <property name="employeeDAO" ref="employeeRepositories " /> 
     </bean> 
0

Проблема с ниже заявления

<bean id="employeeRepositories" class="com.nousinfo.tutorial.dao.EmployeeRepositories"/> 

EmployeeRepositories - это интерфейс. Вы не можете создать компонент для интерфейса.

Вы должны предоставить класс реализации в компоненте

<bean id="employeeRepositories" class="<Implementation class>"/> 

если вы используете jpa:repositories тега, то проверьте, было ли при условии @Repository тега в классе реализации EmployeeRepository как

@Repository 
class EmployeeReporsitoriesImpl implements EmployeeReporsitories