开发者社区> 问答> 正文

自定义classload没法加载jar中的spring配置文件??报错

自己谢了个jar,spring工程的,同时依赖了一些外部的jar。把他们一块放在了D:\test\lib\xx.jar(若干的依赖包)和d:\test\myjar.jar(依赖lib下的包),通过自定义加载器,加载myjar.jar中的main方法执行程序,发现报错:貌似是没有读取我的jar中的spring配置文件,没有注入对象所致。 

Exception in thread "main" java.lang.reflect.InvocationTargetException 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at com.tencent.load.AlexClassLoad.main(AlexClassLoad.java:127) 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dayHotDao' is defined 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)
at 


我的自定义classload如下: 

public class AlexClassLoad  extends URLClassLoader { 
    private FileInputStream input = null;  //文件输入流    
    private ByteArrayOutputStream out = null;  //字节数组输出流    
    private String[] url = null;  //类文件加载路径    
    private byte[] data = null; //类文件字节码    
    private String extensionalName = ""; //类文件扩展名    
   
    public AlexClassLoad(URL[] urls) throws Exception{    
        super(urls);    
        this.url = new String[urls.length];    
        for (int i = 0; i < urls.length; i++) {    
             this.url[i] = urls[i].toURI().toString();    
        }    
    }    
        
    private void setFilePath() {    
        for (int i = 0; i < this.url.length; i++) {    
            if (this.url[i].substring(0,4).toLowerCase().equals("file") == true) {    
                this.url[i] = this.url[i].substring(5);    
            }    
        }    
    }    
   
    private byte[] getFileData(String name) {    
        try {    
            this.setFilePath();    
            for (String url : this.url) {    
                String fileName = url + name.replace('.', '/').concat(".") + this.getExtensionalName();   
                input = new FileInputStream(new File(fileName));    
                if (input != null) {    
                    break;    
                }    
            }              
                
            out = new ByteArrayOutputStream();    
            data = new byte[1024];    
            int len = -1;    
            while ((len = input.read(data)) != -1) {    
                out.write(data, 0, len);    
            }    
            data = out.toByteArray();    
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {    
            try {    
                if (input != null)    
                    input.close();    
                if (out != null)    
                    out.close();    
                return data;    
            } catch (Exception e) {    
                e.printStackTrace();    
                return null;    
            }    
        }    
    }    
   
    protected Class findClassByName(String name) {    
        try {    
            byte[] data = this.getFileData(name);    
            if (data == null) {    
                return null;    
            }    
            return this.defineClass(name, data, 0, data.length);    
        } catch (Exception e) {    
            e.printStackTrace();    
            return null;    
        }    
   
    }    
   
    public Class loadClass(String name) {    
        Class c = null;            
        try {    
            c = super.loadClass(name);            
        } catch (ClassNotFoundException e) {    
            e.printStackTrace();    
        } finally {    
            if (c == null) //父类默认方法没有加载到指定类时,使用自定义方法查找    
                c = this.findClassByName(name);    
            return c;    
        }    
    }   


求原因?打下帮我改改白~ 加载器不是很懂~ 

展开
收起
爱吃鱼的程序员 2020-06-22 21:35:52 771 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    我看到谢了个,轻轻笑了。没别意思啊^-^,帮顶一下
    ?谢了个~packageorg.lsqt.components.dao.dbutil;




    importjava.sql.CallableStatement;
    importjava.sql.Connection;
    importjava.sql.DriverManager;
    importjava.sql.ResultSet;
    importjava.sql.SQLException;
    importjava.util.ArrayList;
    importjava.util.List;
    importjava.util.Properties;


    importjavax.naming.InitialContext;
    importjavax.naming.NamingException;
    importjavax.sql.DataSource;


    importorg.apache.commons.dbutils.QueryRunner;
    importorg.apache.commons.dbutils.handlers.ArrayListHandler;
    importorg.apache.commons.lang.StringUtils;
    importorg.apache.log4j.Logger;


    importorg.lsqt.components.dao.suport.DataRow;
    importorg.lsqt.components.dao.suport.DataSet;
    importorg.lsqt.components.dao.suport.DataTable;
    importorg.lsqt.components.dao.suport.DbHelper;
    importorg.lsqt.components.dao.suport.ParamType;






    /
     <pre>
     
     
     功能说明: 
     
     该执行器优先使用JNDI配置的数据源,其次才是jdbc数据源
       该SQL执行器,提供简易并直接的SQL语句操作数据库.
     
      该SQL执行器不依赖于任何第三方的数据源创建 
       (注:在多个service层内调用多个执行器,没有事务控制)
     
     
     编写日期:2011-4-21
     作者:袁Sky
     
     
     历史记录
     修改日期:2012-3-10
     修改人:袁Sky
     修改内容:
     
      1.添加JNDI支持
     
      2.添加存储过程执行支持
     
    </pre>
     
    /
    publicclassSqlExecutor{


    /
    /
    privatestaticfinalLoggerLOGGER=Logger.getLogger(SqlExecutor.class);
    /
    /
    privatestaticStringUSERNAME;
    /
    **/
    privatestaticStringPASSWORD;
    /
    /
    privatestaticStringURL;
    /
    **/
    privatestaticStringDRIVERCLASSNAME;
    /
    /
    privatestaticStringJNDINAME;
    /
    **/
    privatestaticDataSourcedataSource;
    /
    /
    privatestaticbooleanhasJndiDataSource;
    /
    /
    privatestaticPropertiesproperties=newProperties();

    static{
    loadConfigFile();
    hasJndiDataSource=loadJndiDataSource();

    if(hasJndiDataSource==false){
    try{
    Class.forName(DRIVERCLASSNAME);
    }catch(ClassNotFoundExceptione){
    e.printStackTrace();
    }
    }
    }

    privatestaticvoidloadConfigFile(){
    try{
    <spanstyle="background-color:#E53333;">properties.load(SqlExecutor.class.getResourceAsStream("/dbconfig.properties"));
    LOGGER.debug(properties);

    USERNAME=properties.getProperty("username");
    PASSWORD=properties.getProperty("password");
    URL=properties.getProperty("url");
    DRIVERCLASSNAME=properties.getProperty("driverClassName");

    JNDINAME=properties.getProperty("jndiName");

    }catch(Exceptione){
    try{
    LOGGER.error("notfounddataSource'sconfigurationfile");
    thrownewException(e.getMessage());
    }catch(Exceptione1){
    e1.printStackTrace();
    }
    }
    }

    privatestaticbooleanloadJndiDataSource(){
    try{
    if(StringUtils.isNotEmpty(JNDINAME)){
    InitialContextcontext=newInitialContext();
    dataSource=(DataSource)context.lookup(JNDINAME);
    }
    }catch(NamingExceptione){
    LOGGER.warn("havenoJNDIconfigfound");
    returnfalse;
    }
    returnfalse;
    }


    privatestatic ConnectiongetConnection(){
    try{
    if(hasJndiDataSource){
    LOGGER.debug("database'sconnectionfromJNDIdataSource");
    returndataSource.getConnection();
    }else{
    Connectionconn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
    LOGGER.debug("database'sconnectionfromDriverManager");
    returnconn;
    }
    }catch(SQLExceptione){
    LOGGER.debug(e);
    e.printStackTrace();
    }
    returnnull;
    }

    //-------------------------------------------------------------------------------
    /

    处理参数占位符字符串
    @paramparamValues paramValues
    <aclass='referer'target='_blank'>@returnprocessprocedureParamHold
    /
    privatestaticStringprocessProcedureParamHold(Object[]paramValues){
    StringholdString="";
    intholdLength=paramValues.length;
    for(inti=0;i<holdLength;i++){
    if(i!=holdLength-1){
    holdString="?,"+holdString;
    }else{
    holdString=holdString+"?";
    }
    }
    LOGGER.debug(holdString);
    returnholdString;
    }

    /**
    执行存储过程,返回结果集
    @paramprocedureName存储过程名称
    <aclass='referer'target='_blank'>@returnDataSet 
    /
    publicstaticDataSetexecuteProcedure(finalStringprocedureName){
    finalDataSetDATASET=newDataSet();
    CallableStatementcstmt=null;
    ResultSetrs=null;
    Connectioncon=null;
    try{
    con=getConnection();
    cstmt=con.prepareCall("{call"+procedureName+"()}");


    booleanhasResults=cstmt.execute();


    while(hasResults){
    DataTabledt=newDataTable();


    rs=cstmt.getResultSet();
    intcolCount=rs.getMetaData().getColumnCount();
    while(rs.next()){
    DataRowrow=newDataRow();
    for(inti=0;i<colCount;i++){
    row.add(rs.getObject(i+1));
    }
    dt.add(row);
    }
    DATASET.add(dt);
    hasResults=cstmt.getMoreResults();
    }
    }catch(Exceptione){
    LOGGER.error("procedureexecutefail==>"+e.getMessage());
    returnnull;
    }finally{
    DbHelper.destroy(con,cstmt,rs);
    }


    returnDATASET;
    }

    /**
    执行只带输入参数的存储过程
    @paramprocedureName 存储过程名称
    @paramparamValues入参值
    <aclass='referer'target='_blank'>@returnDataSet数据集
    /
    publicstaticDataSetexecuteProcedure(finalStringprocedureName,finalObject[]paramValues){
    finalDataSetDATASET=newDataSet();
    CallableStatementcstmt=null;
    ResultSetrs=null;
    Connectioncon=null;
    try{
    con=getConnection();
    cstmt=con.prepareCall("{call"+procedureName+"("+processProcedureParamHold(paramValues)+")}");


    booleanhasResults=cstmt.execute();


    while(hasResults){
    DataTabledt=newDataTable();


    rs=cstmt.getResultSet();
    intcolCount=rs.getMetaData().getColumnCount();
    while(rs.next()){
    DataRowrow=newDataRow();
    for(inti=0;i<colCount;i++){
    row.add(rs.getObject(i+1));
    }
    dt.add(row);
    }
    DATASET.add(dt);
    hasResults=cstmt.getMoreResults();
    }
    }catch(Exceptione){
    LOGGER.error("procedureexecutefail==>"+e.getMessage());
    returnnull;
    }finally{
    DbHelper.destroy(con,cstmt,rs); 
    }

    returnDATASET;
    }

    /
    存储过程调用(返回结果集+输出参数+执行系列更新语句),调用时显示指定入参和输出参数据数据类型
     
    @paramprocedureName存储过程名称
    @paramparamValues入参值和输出参数的值
    @paramparamValueTypes储存过程入参和输出参数据的数据类型:ParamType.String待
    <aclass='referer'target='_blank'>@returnDataSet数据集
    /
    publicstaticDataSetexecuteProcedure(finalStringprocedureName,finalObject[]paramValues,finalint[]paramValueTypes){
    if(paramValues.length!=paramValueTypes.length){
    LOGGER.error("procedureexecutefail,Parametersandparametertypesvalue,thelengthnotequal ");
    returnnull;
    }


    finalDataSetDATASET=newDataSet();


    StringsqlHold=processProcedureParamHold(paramValues);
    CallableStatementcstmt=null;
    ResultSetrs=null;
    Connectioncon=null;
    try{
    con=getConnection();
    cstmt=con.prepareCall("{call"+procedureName+"("+sqlHold+")}");


    List<Integer>outputParamIndex=newArrayList<Integer>(); 
    for(inti=0;i<paramValues.length;i++){
    if(paramValues[i]==ParamType.HOLDER){
    cstmt.registerOutParameter(i+1,paramValueTypes[i]);
    outputParamIndex.add(i+1);
    }else{
    cstmt.setObject(i+1,paramValues[i]);
    }
    }


    booleanhasResults=cstmt.execute();


    //处理输出参数值
    List<Object>outputValues=newArrayList<Object>();
    for(inti=0;i<outputParamIndex.size();i++){
    outputValues.add(cstmt.getObject(outputParamIndex.get(i)));
    }


    DATASET.setOutputParams(outputValues.toArray(newObject[outputValues.size()]));


    while(hasResults){
    DataTabledt=newDataTable();


    rs=cstmt.getResultSet();//---取得第一个结果集
    intcolCount=rs.getMetaData().getColumnCount();
    while(rs.next()){
    DataRowrow=newDataRow();
    for(inti=0;i<colCount;i++){
    row.add(rs.getObject(i+1));
    }
    dt.add(row);
    }
    DATASET.add(dt);
    hasResults=cstmt.getMoreResults();
    }
    }catch(Exceptione){
    LOGGER.error("executeprocedurefail==>"+e.getMessage());
    returnnull;
    }finally{
    DbHelper.destroy(con,cstmt,rs); 
    }
    returnDATASET;
    }



    /**
    执行更新的SQL语句
    @paramsql
    <aclass='referer'target='_blank'>@return
    /
    publicstaticbooleanexecuteSql(Stringsql){
    QueryRunnerrun=newQueryRunner();
    Connectionconn=getConnection();
    try{
    returnrun.update(conn,sql)>0;
    }catch(SQLExceptionex){
    LOGGER.error("executesqlfail==>"+ex.getMessage());
    returnfalse;
    }finally{
    DbHelper.destroy(conn,null,null);
    }
    }

    publicstaticbooleanexecuteSql(Stringsql,Object[]paramValues){
    QueryRunnerrun=newQueryRunner();
    Connectionconn=getConnection();
    try{
    returnrun.update(conn,sql,paramValues)>0;
    }catch(SQLExceptionex){
    LOGGER.error("executesqlfail==>"+ex.getMessage());
    returnfalse;
    }finally{
    DbHelper.destroy(conn,null,null);
    }
    }

    /**
    批量执行SQL更新语句
    @paramsql带占位符的SQL语句
    @paramdataTable参数数据表格 
    /
    publicstaticbooleanexecuteSql(Stringsql,Object[][]dataTable){
    QueryRunnerrun=newQueryRunner();
    Connectionconn=getConnection();
    try{

     returnrun.batch(conn,sql,dataTable).length>0;
     
    }catch(SQLExceptionex){
    LOGGER.debug("executesqlfail==>"+ex.getMessage());
    returnfalse;
    }
    finally{
      DbHelper.destroy(conn,null,null);
    }
    }


    /**
    执行查询语句,返回二维结果集
    @paramsql
    <aclass='referer'target='_blank'>@return
    <aclass='referer'target='_blank'>@throwsSQLException
    /
    publicstaticList<Object[]>executeSqlQuery(Stringsql){

    QueryRunnerrun=newQueryRunner();
    Connectionconn=getConnection();
    try{
    return run.query(conn,sql,newArrayListHandler(){
    @Override
    protectedObject[]handleRow(ResultSetrs)throwsSQLException{
    returnsuper.handleRow(rs);
    }
    });
    }catch(SQLExceptionex){
    LOGGER.error("executesqlfail==>"+ex.getMessage());
    returnnull;
    }finally{
    DbHelper.destroy(conn,null,null);
    }
    }


    /**
    执行带"?"占位符的查询语句,返回二维结果集
    @paramsql
    @paramparamValues
    <aclass='referer'target='_blank'>@return
    <aclass='referer'target='_blank'>@throwsSQLException
    /
    publicstaticList<Object[]>executeSqlQuery(Stringsql,Object[]paramValues){
    QueryRunnerrun=newQueryRunner();
    Connectionconn=getConnection();
    try{
    returnrun.query(conn,sql,newArrayListHandler(){
    @Override
    protectedObject[]handleRow(ResultSetrs)throwsSQLException{
    returnsuper.handleRow(rs);
    }
    },paramValues);
    }catch(SQLExceptionex){
    LOGGER.error("executesqlfail==>"+ex.getMessage());
    returnnull;
    }finally{
    DbHelper.destroy(conn,null,null);
    }
    }
    }




    谢谢阿,我这个自定义加载怎么搞定那~就是读取了配置文件,怎么跟spring整合那~<?xmlversion="1.0"encoding="UTF-8"?>
    <beansxmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!--wicket的web框架用-->
      <beanid="consoleApplication"class="org.lsqt.content.web.wicket.ConsoleApplication"/>


    <!--spring加载xml属性配置-->
    <beanclass="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <propertyname="location"value="classpath:springConfig.properties"/>
    </bean>




    <!--common-->
    <importresource="applicationContext-dataSource.xml"/>
    <importresource="applicationContext-hibernate.xml"/>
    <importresource="applicationContext-aop.xml"/>
    <importresource="applicationContext-ehcache.xml"/>
    <importresource="application-spring-mvc.xml"/>

    <spanstyle="background-color:#E53333;"><context:annotation-config/>
    <spanstyle="background-color:#E53333;">  <context:component-scanbase-package="org.lsqt"/>
    </beans>
    不同myjar.jar由JDK的ApplicationClassLoader加载而你自己定义的classLoader去加载xx.jar那么在myjar中是找不到xx.jar中的东西的建议学习一下OSGi,对classLoader应用的典型好的我看看谢谢阿

    2020-06-22 21:36:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多