Добавление TransactionManager в Hibernate Spring

Получение ошибки при добавлении Transaction-Manager. Что случилось? : / Несколько возможных ответов относятся к отсутствию некоторых библиотек гибернации. Однако кажется, что все они сохраняются. Как это побороть? Также я хочу добавить несколько тестовых данных в свою базу данных. В какой класс лучше вставить? Спасибо.

ОШИБКА:

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception 
parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested
 exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

Диспетчер-сервлет:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="miniVLE.controller" />
    <context:component-scan base-package="miniVLE.service" />
    <context:component-scan base-package="miniVLE.beans" />
    <context:component-scan base-package="miniVLE.dao" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>

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


    <!-- Connects to the database based on the jdbc properties information-->
    <bean id="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name ="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name ="url" value="jdbc:derby://localhost:1527/minivledb"/>
        <property name ="username" value="root"/>
        <property name ="password" value="123" />
    </bean>

     <!-- Declares hibernate object -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect"> ${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
        <!-- A list of all the annotated bean files, which are mapped with database tables-->
        <property name="annotatedClasses">
            <list>
                <value> miniVLE.beans.Course </value>
                <value> miniVLE.beans.Student </value>
                <value> miniVLE.beans.Department </value>  
                <value> miniVLE.beans.Module </value>  
                <value> miniVLE.beans.TimeSlot </value> 
            </list>
        </property>
    </bean>

    <!-- Declare a transaction manager-->
    <bean   id="hibernateTransactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

DAO:

@Repository
public class MiniVLEDAOImplementation implements MiniVLEDAO{

    // Used for communicating with the database
    @Autowired
    private SessionFactory sessionFactory;

@Override
public void addStudentToDB(Student student) {         
    sessionFactory.getCurrentSession().saveOrUpdate(student);        
}....

Сервис:

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class StudentService implements IStudentService{

    @Autowired
    MiniVLEDAOImplementation dao;    

    public StudentService() {
         System.out.println("*** StudentService instantiated");
    }

    @Override
    public Student getStudent(String urn){
        Student s = dao.getStudentFromDB(urn);
        return s;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void addStudent(Student student) {
        dao.addStudentToDB(student);
    }...

Контроллер:

@Controller
public class miniVLEController {

    @Autowired
    StudentService studentService;

После добавления aopalliance-1.0.jar появляется следующая ОШИБКА:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.service.StudentService miniVLE.controller.miniVLEController.studentService; nested exception is java.lang.IllegalArgumentException: Can not set miniVLE.service.StudentService field miniVLE.controller.miniVLEController.studentService to sun.proxy.$Proxy536

Одним из решений было добавить <aop:aspectj-autoproxy proxy-target-class="true"/> в сервлет-диспетчер. следующая Ошибка:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController' defined in file 
[C:\Users\1\Documents\NetBeansProjects\com3014_mini_VLE\build\web\WEB-
INF\classes\miniVLE\controller\miniVLEController.class]: BeanPostProcessor before 
instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: 
org/aspectj/lang/annotation/Aspect

person exomen    schedule 24.04.2013    source источник


Ответы (2)


Вам нужно добавить зависимость aopalliance.jar. Если вы используете maven:

<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>
person Evgeni Dimitrov    schedule 24.04.2013
comment
Что делать, если я не использую Maven? :) - person exomen; 24.04.2013
comment
Вы можете скачать его со страницы findjar.com/jar/aopalliance/jars /aopalliance-1.0.jar.html, а затем добавьте его в свой путь к классам. - person Evgeni Dimitrov; 24.04.2013
comment
У вас есть установщик для @Autowired StudentService studentService; - person Evgeni Dimitrov; 25.04.2013
comment
Также обратитесь к этому вопросу stackoverflow.com/questions/10570322/ - person Evgeni Dimitrov; 25.04.2013
comment
Просто предложение. Если вы (пока) не используете maven, вам стоит взглянуть на него! Я использую его сейчас даже для самых маленьких проектов, и он очень хорошо помогает вам в решении подобных проблем. Иногда происходит что-то, что приводит к WTH ??, но через некоторое время вы привыкаете решать эти проблемы :) - person Martin Frey; 25.04.2013

После эскалации проблемы:

Необходимо найти aspectjrt-1.x.x.jar, который отсутствовал, чтобы преодолеть последнюю ошибку, а затем преодолеть ошибку org.aspectj.util.PartialOrder.PartialComparable, вам нужно получить aspectjtools-1.X.X.jar

здесь я нашел все необходимые мне дополнительные библиотеки http://www.jarfinder.com/index.php/java/info/org.aspectj.lang.NoAspectBoundException

person exomen    schedule 24.04.2013