java.lang.ClassCastException:com.sun.proxy.$ Proxy0无法转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate [英] java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate

查看:129
本文介绍了java.lang.ClassCastException:com.sun.proxy.$ Proxy0无法转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Spring Framework应用程序中实现有关声明式事务的本教程,但无法正常工作,因为当我尝试执行 MainApp 类以测试应用程序行为时,我得到了一个错误:

http://www.tutorialspoint.com/spring/declarative_management.htm

所以我只有一个 StudentDAO 接口,我只定义了我想要的CRUD方法:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;

import javax.sql.DataSource;

/** Interfaccia che definisce i metodi che implementano le operazioni di CRUD
 *  che vogliamo implementare nel nostro DAO:
 */
public interface StudentDAO {

    /**
     * Questo metodo viene usato per inizializzare le risorse del database cioè
     * la connessione al database:
     */
    public void setDataSource(DataSource ds);

    /**
     * Questo metodo serve a creare un record nella tabella Student e nella
     * tabella Marks:
     */
    public void create(String name, Integer age, Integer marks, Integer year);

    /**
     * Questo metodo serve ad elencare tutti i record all'interno della tabella
     * Studend e della tabella Marks
     */
    public List<StudentMarks> listStudents();
}

然后,我有一个 StudentMark 类,可以表示我的实体,以保留在数据库的第二张表上:

package org.andrea.myexample.myDeclarativeTransactionSpring;

// Rappresenta l'entity:
public class StudentMarks {

    // Proprietà:
    private Integer age;
    private String name;
    private Integer id;
    private Integer marks;
    private Integer year;
    private Integer sid;

    // Metodi Getter & Setter:
    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setMarks(Integer marks) {
        this.marks = marks;
    }

    public Integer getMarks() {
        return marks;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    public Integer getYear() {
        return year;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public Integer getSid() {
        return sid;
    }
}

然后,我有一个实现 RowMapper 接口的类 StudentMarksMapper :

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;


/** Classe che implementa l'interfaccia RowMapper. Si tratta di un'interfaccia
 *  usata da JdbcTemplate per mappare le righe di un ResultSet (oggetto che 
 *  contiene l'insieme delle righe restituite da una query SQL) riga per riga.
 *  Le implementazioni di questa interfaccia mappano ogni riga su di un oggetto
 *  risultante senza doversi preoccupare della gestione delle eccezioni poichè
 *  le SQLException saranno catturate e gestite dalla chiamata a JdbcTemplate.
 */
public class StudentMarksMapper implements RowMapper<StudentMarks> {

    /** Implementazione del metodo dell'interfaccia RowMapper che mappa una 
     *  specifica riga della tabella su di un oggetto Student
     * 
     *  @param Un oggetto ResultSet contenente l'insieme di tutte le righe
     *         restituite dalla query
     * 
     *  @param L'indice che indentifica una specifica riga
     * 
     *  @return Un nuovo oggetto Student rappresentante la riga selezionata
     *          all'interno dell'oggetto ResultSet
     * 
     *  @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
     */
    public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {

        StudentMarks studentMarks = new StudentMarks();

        studentMarks.setId(rs.getInt("id"));
        studentMarks.setName(rs.getString("name"));
        studentMarks.setAge(rs.getInt("age"));
        studentMarks.setSid(rs.getInt("sid"));
        studentMarks.setMarks(rs.getInt("marks"));
        studentMarks.setYear(rs.getInt("year"));

        return studentMarks;
    }
}

在它旁边是StudentDAO接口的 StudentJDBCTemplate 类:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Classe che fornisce l'implementazione per il nostro DAO le cui funzionalità
 * di CRUD sono state definite tramite l'interfaccia StudentDAO
 */
public class StudentJDBCTemplate implements StudentDAO {

    // Utility per l'accesso alla sorgente dati
    private JdbcTemplate jdbcTemplateObject;

    /**
     * Metodo Setter per l'Injection della dipendenza relativa alla sorgente
     * dati. Tale metodo inoltre costruisce anche l'oggetto istanza di
     * JdbcTemplate usato per interagire con i dati nel database.
     * 
     * @param la sorgente dati
     */
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    /**
     * Metodo relativo all'operazione di CREATE che inserisce un nuovo record
     * all'interno della tabella Student ed un correlato nuovo record nella
     * tabella Marks.
     */
    public void create(String name, Integer age, Integer marks, Integer year) {

        try {
            // Query che inserisce nome ed età nella tabella Student:
            String SQL1 = "insert into Student (name, age) values (?, ?)";
            // Esegue la query passandogli anche i valori effettivi da inserire:
            jdbcTemplateObject.update(SQL1, name, age);

            // Seleziona l'ultimo studente inserito nella tabella Marks:
            String SQL2 = "select max(id) from Student";
            // Esegue la query e mette il risultato (l'ID) in sid:
            int sid = jdbcTemplateObject.queryForInt(SQL2);

            /**
             * Query che inserisce un nuovo record nella tabella Marks. Il
             * record rappresenta il voto per l'ultimo studente inserito nella
             * tabella Student:
             */
            String SQL3 = "insert into Marks(sid, marks, year) "
                    + "values (?, ?, ?)";
            // Esegue la query passandogli anche i valori effettivi da inserire:
            jdbcTemplateObject.update(SQL3, sid, marks, year);

            System.out.println("Created Name = " + name + ", Age = " + age);

            // SIMULA UNA RuntimeExceptio:
            throw new RuntimeException("Simulazione di una condizione d'errore");
        } catch (DataAccessException e) {       // GESTIONE DELL'ECCEZIONE
            System.out.println("Errore nella creazione dei record, esegue rollback");
            throw e;
        }
    }

    /**
     * Metodo relativo all'operazione di READ che recupera la lista degli
     * studenti e dei relativi voti
     * 
     * @return La lista di oggetti che rappresentano uno studente ed i suoi voti
     *         correlati
     */
    public List<StudentMarks> listStudents() {

        /**
         * Query che estrae la lista di tutti i record nella tabella Student e
         * che per ogni record in tale tabella estrae i relativi record
         * correlati nella tabella Marks
         */
        String SQL = "select * from Student, Marks where Student.id=Marks.sid";

        /**
         * Ottengo la lista degli oggetti StudentMarks, corrispondenti ognuno ad
         * un record della tabella Student con i correlati vori rappresentati
         * dai record della tabella Marks, invocando il metodo query 
         * sull'oggetto JdbcTemplate passandogli i seguenti parametri.
         * 
         * @param La query per creare il preparated statement
         * @param Un oggetto che implementa RowMapper che viene usato per
         *        mappare una singola riga della tabella su di un oggetto Java
         */
        List<StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
                                                     new StudentMarksMapper());
        return studentMarks;
    }
}

这是用于测试应用程序的 MainApp 类:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

// Classe principale:
public class MainApp {

    public static void main(String[] args) {

        /**
         * Crea il contesto in base alle impostazioni dell'applicazione definite
         * nel file Beans.xml
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        /**
         * Recupera un bean avente id="studentJDBCTemplate" nel file di
         * configurazione Beans.xml
         */
        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

        System.out.println("------Creazione dei record--------");
        // Creo i record nelle tabelle Studend e Marks:
        studentJDBCTemplate.create("Zara", 11, 99, 2010);
        studentJDBCTemplate.create("Nuha", 20, 97, 2010);
        studentJDBCTemplate.create("Ayan", 25, 100, 2011);

        System.out.println("------Elenca tutti i record--------");
        // Recupera la lista degli studenti con i voti ad essi associati:
        List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();

        for (StudentMarks record : studentMarks) {      // e li stampa
            System.out.print("ID : " + record.getId());
            System.out.print(", Name : " + record.getName());
            System.out.print(", Marks : " + record.getMarks());
            System.out.print(", Year : " + record.getYear());
            System.out.println(", Age : " + record.getAge());
        }
    }
}

最后,这是我的 Beans.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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-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/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- Initializazione della sorgente dati: -->
    <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/SpringTestDb" />
        <property name="username" value="root" />
        <property name="password" value="aprile12" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="create" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="createOperation"
            expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate.create(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
    </aop:config>

    <!-- Inizializzazione del Transaction Manager: -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Definizione del bean che rappresenta il DAO studentJDBCTemplate: -->
    <bean id="studentJDBCTemplate" class="org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

问题是,当我尝试运行我的 MainApp 类时,我得到了以下错误信息:

INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate
    at org.andrea.myexample.myDeclarativeTransactionSpring.MainApp.main(MainApp.java:22)

在此错误消息中,说问题出在MainApp类的第22行上……就是当我尝试获取具有ID ="studentJDBCTemplate:

的bean时.

StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

问题出在哪里?我该怎么解决?

Tnx

安德里亚

解决方案

选项1,更改配置以在接口级别注入事务:

<aop:config>
    <aop:pointcut id="createOperation"
        expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentDAO.create(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
</aop:config>

并获取该bean作为该接口的实例:

StudentDAO studentDao = (StudentDAO) context.getBean("studentJDBCTemplate");

选项2,指示代理应使用proxy-target-class属性扩展目标类:

<aop:config proxy-target-class="true">
    ...
</aop:config>

第一个选项是更简洁的选项,但是坦率地说,我更愿意在Spring bean XML中使用@Transactional批注而不是AOP声明.有时很难使后者正确,如果您没有对组件进行特定的事务性测试,您将不一定会注意到事情不正确.

I am trying to implement this tutorial about Declarative Transaction in Spring Framework application but don't work because when I try to execute the MainApp class to test the application behavior I obtain an error:

http://www.tutorialspoint.com/spring/declarative_management.htm

So I have the StudentDAO interface in wich I only define the CRUD method that I want:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;

import javax.sql.DataSource;

/** Interfaccia che definisce i metodi che implementano le operazioni di CRUD
 *  che vogliamo implementare nel nostro DAO:
 */
public interface StudentDAO {

    /**
     * Questo metodo viene usato per inizializzare le risorse del database cioè
     * la connessione al database:
     */
    public void setDataSource(DataSource ds);

    /**
     * Questo metodo serve a creare un record nella tabella Student e nella
     * tabella Marks:
     */
    public void create(String name, Integer age, Integer marks, Integer year);

    /**
     * Questo metodo serve ad elencare tutti i record all'interno della tabella
     * Studend e della tabella Marks
     */
    public List<StudentMarks> listStudents();
}

Then I have StudentMark class that rappresent my entity to persist on the 2 table on the database:

package org.andrea.myexample.myDeclarativeTransactionSpring;

// Rappresenta l'entity:
public class StudentMarks {

    // Proprietà:
    private Integer age;
    private String name;
    private Integer id;
    private Integer marks;
    private Integer year;
    private Integer sid;

    // Metodi Getter & Setter:
    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setMarks(Integer marks) {
        this.marks = marks;
    }

    public Integer getMarks() {
        return marks;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    public Integer getYear() {
        return year;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public Integer getSid() {
        return sid;
    }
}

Then I have the class StudentMarksMapper that implement RowMapper interface:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;


/** Classe che implementa l'interfaccia RowMapper. Si tratta di un'interfaccia
 *  usata da JdbcTemplate per mappare le righe di un ResultSet (oggetto che 
 *  contiene l'insieme delle righe restituite da una query SQL) riga per riga.
 *  Le implementazioni di questa interfaccia mappano ogni riga su di un oggetto
 *  risultante senza doversi preoccupare della gestione delle eccezioni poichè
 *  le SQLException saranno catturate e gestite dalla chiamata a JdbcTemplate.
 */
public class StudentMarksMapper implements RowMapper<StudentMarks> {

    /** Implementazione del metodo dell'interfaccia RowMapper che mappa una 
     *  specifica riga della tabella su di un oggetto Student
     * 
     *  @param Un oggetto ResultSet contenente l'insieme di tutte le righe
     *         restituite dalla query
     * 
     *  @param L'indice che indentifica una specifica riga
     * 
     *  @return Un nuovo oggetto Student rappresentante la riga selezionata
     *          all'interno dell'oggetto ResultSet
     * 
     *  @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
     */
    public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {

        StudentMarks studentMarks = new StudentMarks();

        studentMarks.setId(rs.getInt("id"));
        studentMarks.setName(rs.getString("name"));
        studentMarks.setAge(rs.getInt("age"));
        studentMarks.setSid(rs.getInt("sid"));
        studentMarks.setMarks(rs.getInt("marks"));
        studentMarks.setYear(rs.getInt("year"));

        return studentMarks;
    }
}

Next to it this is StudentJDBCTemplate class that StudentDAO interface:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Classe che fornisce l'implementazione per il nostro DAO le cui funzionalità
 * di CRUD sono state definite tramite l'interfaccia StudentDAO
 */
public class StudentJDBCTemplate implements StudentDAO {

    // Utility per l'accesso alla sorgente dati
    private JdbcTemplate jdbcTemplateObject;

    /**
     * Metodo Setter per l'Injection della dipendenza relativa alla sorgente
     * dati. Tale metodo inoltre costruisce anche l'oggetto istanza di
     * JdbcTemplate usato per interagire con i dati nel database.
     * 
     * @param la sorgente dati
     */
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    /**
     * Metodo relativo all'operazione di CREATE che inserisce un nuovo record
     * all'interno della tabella Student ed un correlato nuovo record nella
     * tabella Marks.
     */
    public void create(String name, Integer age, Integer marks, Integer year) {

        try {
            // Query che inserisce nome ed età nella tabella Student:
            String SQL1 = "insert into Student (name, age) values (?, ?)";
            // Esegue la query passandogli anche i valori effettivi da inserire:
            jdbcTemplateObject.update(SQL1, name, age);

            // Seleziona l'ultimo studente inserito nella tabella Marks:
            String SQL2 = "select max(id) from Student";
            // Esegue la query e mette il risultato (l'ID) in sid:
            int sid = jdbcTemplateObject.queryForInt(SQL2);

            /**
             * Query che inserisce un nuovo record nella tabella Marks. Il
             * record rappresenta il voto per l'ultimo studente inserito nella
             * tabella Student:
             */
            String SQL3 = "insert into Marks(sid, marks, year) "
                    + "values (?, ?, ?)";
            // Esegue la query passandogli anche i valori effettivi da inserire:
            jdbcTemplateObject.update(SQL3, sid, marks, year);

            System.out.println("Created Name = " + name + ", Age = " + age);

            // SIMULA UNA RuntimeExceptio:
            throw new RuntimeException("Simulazione di una condizione d'errore");
        } catch (DataAccessException e) {       // GESTIONE DELL'ECCEZIONE
            System.out.println("Errore nella creazione dei record, esegue rollback");
            throw e;
        }
    }

    /**
     * Metodo relativo all'operazione di READ che recupera la lista degli
     * studenti e dei relativi voti
     * 
     * @return La lista di oggetti che rappresentano uno studente ed i suoi voti
     *         correlati
     */
    public List<StudentMarks> listStudents() {

        /**
         * Query che estrae la lista di tutti i record nella tabella Student e
         * che per ogni record in tale tabella estrae i relativi record
         * correlati nella tabella Marks
         */
        String SQL = "select * from Student, Marks where Student.id=Marks.sid";

        /**
         * Ottengo la lista degli oggetti StudentMarks, corrispondenti ognuno ad
         * un record della tabella Student con i correlati vori rappresentati
         * dai record della tabella Marks, invocando il metodo query 
         * sull'oggetto JdbcTemplate passandogli i seguenti parametri.
         * 
         * @param La query per creare il preparated statement
         * @param Un oggetto che implementa RowMapper che viene usato per
         *        mappare una singola riga della tabella su di un oggetto Java
         */
        List<StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
                                                     new StudentMarksMapper());
        return studentMarks;
    }
}

Then this is the MainApp class to test the application:

package org.andrea.myexample.myDeclarativeTransactionSpring;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

// Classe principale:
public class MainApp {

    public static void main(String[] args) {

        /**
         * Crea il contesto in base alle impostazioni dell'applicazione definite
         * nel file Beans.xml
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        /**
         * Recupera un bean avente id="studentJDBCTemplate" nel file di
         * configurazione Beans.xml
         */
        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

        System.out.println("------Creazione dei record--------");
        // Creo i record nelle tabelle Studend e Marks:
        studentJDBCTemplate.create("Zara", 11, 99, 2010);
        studentJDBCTemplate.create("Nuha", 20, 97, 2010);
        studentJDBCTemplate.create("Ayan", 25, 100, 2011);

        System.out.println("------Elenca tutti i record--------");
        // Recupera la lista degli studenti con i voti ad essi associati:
        List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();

        for (StudentMarks record : studentMarks) {      // e li stampa
            System.out.print("ID : " + record.getId());
            System.out.print(", Name : " + record.getName());
            System.out.print(", Marks : " + record.getMarks());
            System.out.print(", Year : " + record.getYear());
            System.out.println(", Age : " + record.getAge());
        }
    }
}

Finnally this is my Beans.xml configuration file:

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

    <!-- Initializazione della sorgente dati: -->
    <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/SpringTestDb" />
        <property name="username" value="root" />
        <property name="password" value="aprile12" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="create" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="createOperation"
            expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate.create(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
    </aop:config>

    <!-- Inizializzazione del Transaction Manager: -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Definizione del bean che rappresenta il DAO studentJDBCTemplate: -->
    <bean id="studentJDBCTemplate" class="org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

the prroblem is that when I try to run my MainApp class I obtain the following error messate:

INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate
    at org.andrea.myexample.myDeclarativeTransactionSpring.MainApp.main(MainApp.java:22)

In this error message say that the problem is on line 22 of the MainApp class...that is simply when I try to obtain the bean having ID="studentJDBCTemplate:

StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

Where is the problem? How can I solve?

Tnx

Andrea

解决方案

Option 1, change your configuration to inject transactions at the interface level:

<aop:config>
    <aop:pointcut id="createOperation"
        expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentDAO.create(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
</aop:config>

and obtain the bean as an instance of that interface:

StudentDAO studentDao = (StudentDAO) context.getBean("studentJDBCTemplate");

Option 2, indicate that the proxy should extend the target class using proxy-target-class attribute:

<aop:config proxy-target-class="true">
    ...
</aop:config>

The first option is the cleaner one, but frankly I'd prefer to use@Transactional annotations rather than AOP declarations within the Spring bean XML. It's sometimes diffucult to get the latter correct and if you don't have specific transactionality tests on your components, you will not necessarily notice that things are incorrect.

这篇关于java.lang.ClassCastException:com.sun.proxy.$ Proxy0无法转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆