【问题标题】:Cannot Initialize a class using the Singleton Method无法使用单例方法初始化类
【发布时间】:2015-06-30 13:57:59
【问题描述】:

我创建了一个获取数据库连接实例的类。但是我收到一个错误,说调用类为空。我将在下面发布我的错误。

现在我有了这段代码的工作和非工作版本。我首先只是将所有内容都塞进一个类中以使其启动并运行,然后开始清理它,这就是我遇到问题的时候。

“createJobTicket”这个类调用DataBaseConnectionDAO的实例

public class createJobTicket {

    //private java.sql.Connection conn = null;
    //private java.sql.Statement stmt = null;
    private static DataBaseConnectionDAO databaseConnection = DataBaseConnectionDAO.getInstance();

    public static HSSFWorkbook getWorkbook(HSSFWorkbook workbook, Long id, Environment env){

     try{

         java.sql.Connection conn =  databaseConnection.getConnection();
         java.sql.Statement stmt = conn.createStatement();
          String sql;
          sql = "SELECT"
                    +" hillcresttooldie.T_PO.id po_id,"
                    +" hillcresttooldie.T_PO.DUE_DATE due_date,"
                    +" hillcresttooldie.T_CUSTOMER.CUSTOMER_NAME customer_name,"
                    +" hillcresttooldie.T_PART.ID part_id,"
                    +" hillcresttooldie.T_PO_PART.PART_QUANTITY part_quantity,"
                    +" hillcresttooldie.T_PART.PART_NUMBER part_number,"
                    +" hillcresttooldie.T_PART.PART_DESCRIPTION part_description,"
                    +" hillcresttooldie.T_PART.PLASMA_HRS_PER_PART plasma_hrs,"
                    +" hillcresttooldie.T_PART.GRIND_HRS_PER_PART grind_hrs,"
                    +" hillcresttooldie.T_PART.MILL_HRS_PER_PART mill_hrs,"
                    +" hillcresttooldie.T_PART.BRAKEPRESS_HRS_PER_PART brakepress_hrs,"
                    +" hillcresttooldie.T_PART.LASER_HRS_PER_PART laser_hrs,"
                    +" hillcresttooldie.T_MATERIAL.MATERIAL_THICKNESS material_thickness"
                    +" FROM hillcresttooldie.T_PO"
                    +" join hillcresttooldie.T_PO_PART"
                    +" on hillcresttooldie.T_PO_PART.PO_ID = hillcresttooldie.T_PO.ID"
                    +" join hillcresttooldie.T_PART"
                    +" on hillcresttooldie.T_PART.ID = hillcresttooldie.T_PO_PART.PART_ID"
                    +" join hillcresttooldie.T_CUSTOMER"
                    +" on hillcresttooldie.T_PO.CUSTOMER_ID = hillcresttooldie.T_CUSTOMER.ID"
                    +" join hillcresttooldie.T_PART_MATERIAL"
                    +" on hillcresttooldie.T_PART.ID = hillcresttooldie.T_PART_MATERIAL.PARTS_ID"
                    +" join hillcresttooldie.T_MATERIAL"
                    +" on hillcresttooldie.T_PART_MATERIAL.materials_id = hillcresttooldie.T_MATERIAL.id"
                    +" where T_PO.id = '"+id+"'";

         ResultSet rs = stmt.executeQuery(sql);

         int index = 0;

         //STEP 5: Extract data from result set
          while(rs.next()){
             int po_id = rs.getInt("po_id");
             String due_date = rs.getString("due_date");
             String customer_name = rs.getString("customer_name");
             int part_id  = rs.getInt("part_id");
             int part_quantity = rs.getInt("part_quantity");
             String part_number = rs.getString("part_number");
             String part_description = rs.getString("part_description");
             BigDecimal plasma_hrs = rs.getBigDecimal("plasma_hrs");
             BigDecimal grind_hrs = rs.getBigDecimal("grind_hrs");
             BigDecimal mill_hrs = rs.getBigDecimal("mill_hrs");
             BigDecimal brakepress_hrs = rs.getBigDecimal("brakepress_hrs");
             BigDecimal laser_hrs = rs.getBigDecimal("laser_hrs");
             double material_thickness = rs.getDouble("material_thickness");


             //Create the Sheet
             String sheetName = index + "-" + customer_name + "-" + part_number;
             HSSFSheet sheet = workbook.createSheet(sheetName);
             //Apply Template to the sheet
             generateTemplate.applyTemplate(workbook, sheet);


             sheet.getRow(1).createCell(1).setCellValue(po_id);
             sheet.getRow(5).getCell(3).setCellValue(customer_name);
             sheet.getRow(5).createCell(8).setCellValue(due_date);
             sheet.getRow(6).getCell(3).setCellValue(part_number);
             sheet.getRow(6).createCell(8).setCellValue(part_quantity);
             sheet.getRow(7).createCell(4).setCellValue(part_description);
             sheet.getRow(7).createCell(8).setCellValue(material_thickness);


             index++;
          }
          //STEP 6: Clean-up environment
          rs.close();
          stmt.close();
          conn.close();

       }catch(SQLException se){
         se.printStackTrace();
         System.out.println("SQL Exeception thrown");
       }catch(Exception e){
          e.printStackTrace();

       }//end try
    return workbook;

    }

您可以注意到以下内容被注释掉了:

//private java.sql.Connection conn = null;
//private java.sql.Statement stmt = null;

这是因为如果我的 IDE 说:

 Cannot make a static reference to the non-static field conn
 Cannot make a static reference to the non-static field stmt

我的 DataBaseConnectionDAO 如下所示:

public class DataBaseConnectionDAO {

    @Inject
    private static Environment env;

    private static DataBaseConnectionDAO instance;

    // Step 1: JDBC props
     String DB_URL = env.getProperty("spring.datasource.url");
     String USER = env.getProperty("spring.datasource.username");
     String PASS = env.getProperty("spring.datasource.password");
     java.sql.Connection conn = null;
     java.sql.Statement stmt = null;

    private DataBaseConnectionDAO() { }

    public static DataBaseConnectionDAO getInstance() {

        if (instance == null) {
            synchronized (DataBaseConnectionDAO.class) {
                if (instance == null) {
                    instance = new DataBaseConnectionDAO();
                }
            }
        }
        return instance;
    }

    public java.sql.Connection getConnection() throws ClassNotFoundException,
            SQLException {

        Class.forName("com.mysql.jdbc.Driver");

        if (conn == null) {

            conn = DriverManager.getConnection(DB_URL, USER, PASS);

        }

        return conn;
    }

}


[DEBUG] com.htd.aop.logging.LoggingAspect - Enter: com.htd.web.rest.PoResource.generateJobTicket() with argument[s] = [16, com.codahale.metrics.servlet.AbstractInstrumentedFilter$StatusExposingServletResponse@1424a144]
[ERROR] com.htd.aop.logging.LoggingAspect - Exception in com.htd.web.rest.PoResource.generateJobTicket() with cause = null
java.lang.NoClassDefFoundError: Could not initialize class com.htd.web.rest.util.createJobTicket
    at com.htd.web.rest.PoResource.generateJobTicket(PoResource.java:332) ~[classes/:na]
    at com.htd.web.rest.PoResource$$FastClassBySpringCGLIB$$cfcd338a.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at com.htd.aop.logging.LoggingAspect.logAround(LoggingAspect.java:49) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at com.htd.web.rest.PoResource$$EnhancerBySpringCGLIB$$4795e29.generateJobTicket(<generated>) [spring-core-4.1.6.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at com.codahale.metrics.servlet.AbstractInstrumentedFilter.doFilter(AbstractInstrumentedFilter.java:104) [metrics-servlet-3.1.1.jar:3.1.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291) [spring-boot-actuator-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:157) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at com.htd.web.filter.CsrfCookieGeneratorFilter.doFilterInternal(CsrfCookieGeneratorFilter.java:34) [classes/:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:96) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) [spring-security-web-4.0.0.RELEASE.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102) [spring-boot-actuator-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_31]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_31]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.20.jar:8.0.20]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_31]

错误:

[DEBUG] com.htd.aop.logging.LoggingAspect - Enter: com.htd.web.rest.PoResource.generateJobTicket() with argument[s] = [16, com.codahale.metrics.servlet.AbstractInstrumentedFilter$StatusExposingServletResponse@613cf2e]
[ERROR] com.htd.aop.logging.LoggingAspect - Exception in com.htd.web.rest.PoResource.generateJobTicket() with cause = null
java.lang.NoClassDefFoundError: Could not initialize class com.htd.web.rest.util.createJobTicket
    at com.htd.web.rest.PoResource.generateJobTicket(PoResource.java:332) ~[classes/:na]
    at com.htd.web.rest.PoResource$$FastClassBySpringCGLIB$$cfcd338a.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]

【问题讨论】:

  • 如果您希望变量在类级别 (private static java.sql.Connection conn = null;),您也需要将变量声明为静态。
  • 关于代码质量的旁注:尝试将冗长的方法分解成许多小的方法。并尽量避免使用 static (它只会使单元测试hard)。
  • 您确定错误是说 DataBaseConnectionDao 为空吗?您的单例实现工作正常...我只测试了实现...所以我无法判断其他部分...
  • 我添加了错误,不得不缩短代码。因为帖子太长,所以我取出了工作代码。
  • @Keppil 即使我按照您的建议进行操作,我也会收到与上面发布的相同的错误。意思是无法创建 createJobTicket,但在我实现单例模式之前我没有遇到问题。

标签: java spring jdbc


【解决方案1】:

您需要首先了解此错误消息的含义:

java.lang.NoClassDefFoundError: Could not initialize class com.htd.web.rest.util.createJobTicket

当 JVM 加载一个类时,它将完成该类的所有静态初始化,即分配给static 字段的任何值并运行任何static { ... } 块。由于这涉及运行 Java 代码,因此此过程可能会引发异常。如果在类的静态初始化过程中抛出异常,则类加载将失败。 Java 会将异常包装在ExceptionInInitializerError 中并抛出它。如果您再次尝试加载同一个类,Java 将断然拒绝加载它,而是抛出带有消息 Could not initialize class ...NoClassDefFoundError

由于这是您看到的错误,我只能得出结论,您的 createJobTicket 类的静态初始化失败,并且上面的异常堆栈跟踪不是来自您第一次尝试使用 createJobTicket 类。例如,如果您的应用程序是 Web 应用程序,请尝试重新启动 Web 应用程序容器,再试一次,看看您第一次是否遇到不同的错误。

createJobTicket 类的静态初始化如下:

    private static DataBaseConnectionDAO databaseConnection = DataBaseConnectionDAO.getInstance();

所以你的DataBaseConnectionDAO.getInstance() 方法一定会抛出异常。

避免此类静态初始化问题的最佳方法是完全避免静态初始化。例如,在下面,我们创建一个方法getDatabaseConnection(),如果尚未设置databaseConnection字段,则设置该方法,并额外调用DAO返回一个JDBC Connection对象:

    private static DataBaseConnectionDAO databaseConnection;

    private static java.sql.Connection getDatabaseConnection() {
        if (databaseConnection == null) {
            databaseConnection = DataBaseConnectionDAO.getInstance();
        }
        return databaseConnection.getConnection();
    }

    public static HSSFWorkbook getWorkbook(HSSFWorkbook workbook, Long id, Environment env){

     try{

         java.sql.Connection conn = getDatabaseConnection();
         // ...

这种方法应该可以阻止您的 createJobTicket 类无法完成静态初始化。但是,请不要期望您的代码在执行此操作后立即开始工作。上述更改无法修复导致静态初始化失败的异常。它所做的只是确保仅在静态初始化类之后才抛出此异常。如果您随后尝试运行您的代码,您应该希望在日志中看到实际的异常,而不是 NoClassDefFoundError

那么,为什么您的 DataBaseConnectionDAO.getInstance() 方法会抛出异常?我的最佳猜测是:

@Inject
private static Environment env;

一些搜索表明您不能使用 Spring 将值注入到这样的静态字段中,因此您可能会遇到 NullPointerException 试图在 null 的环境中查找值。但是,我还没有完全研究这个问题,所以我不能保证这确实是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2021-11-03
    • 2012-08-01
    相关资源
    最近更新 更多