java.lang.ClassCastException:com.sun.proxy.$Proxy0无法强制转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate

java.lang.ClassCastException:com.sun.proxy.$Proxy0无法强制转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate,第1张

概述我试图在Spring Framework应用程序中实现关于声明性事务的本教程,但是不起作用,因为当我尝试执行MainApp类来测试应用程序行为时,我得到一个错误:http://www.tutorialspoint.com/spring/declarative_management.htm所以我有StudentDAO接口我只定义了我想要的CRUD方法:pack

我试图在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

然后我有StudentMark类,它将我的实体暴露在数据库的2表上:

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

它旁边是StudentJDBCTemplate类,即StudentDAO接口:

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 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,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

然后这是测试应用程序的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

最后这是我的Beans.xml配置文件:

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

INFO: Loaded JDBC driver: com.MysqL.jdbc.DriverException 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,更改配置以在接口级别注入事务:

fig>    pointcut ID="createOperation"        Expression="execution(* org.andrea.myexample.myDeclarativeTransactionspring.StudentDAO.create(..))" />    pointcut-ref="createOperation" />

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

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

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

fig proxy-target->    ...

第一个选项是更干净的选项,但坦率地说,我更喜欢在Spring bean XML中使用@Transactional注释而不是AOP声明.有时难以使后者正确,如果您没有对组件进行特定的事务性测试,则不一定会注意到事情是不正确的. 总结

以上是内存溢出为你收集整理的java.lang.ClassCastException:com.sun.proxy.$Proxy0无法强制转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate全部内容,希望文章能够帮你解决java.lang.ClassCastException:com.sun.proxy.$Proxy0无法强制转换为org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1239967.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)