ava.lang.IllegalStateException:BeanFactory未初始化或已关闭-在通过ApplicationContext访问Bean之前调用“刷新”

时间:2018-07-19 05:43:27

标签: java spring javabeans illegalstateexception

我从以下代码行中收到此错误-'ContextHolder.getContext()。getBean(org.apache.tomcat.jdbc.pool.DataSource.class)'有时 (并非一直如此)

在大多数情况下,出现此错误时,程序将在几分钟后重试并恢复。

代码的来源:

import javax.sql.DataSource;
......

public class DAOUtil
{

    public final static Connection getOracleConnection(  ) throws DAOException
    {
        DataSource dataSource = ContextHolder.getContext().getBean(org.apache.tomcat.jdbc.pool.DataSource.class);
        try
        {
            return dataSource.getConnection();
        }
        catch ( SQLException e )
        {
            throw new DAOException( "failed to get connection from data source",e );
        }
    }

  ......
}fr

在Spring上下文中,此org.apache.tomcat.jdbc.pool.DataSource bean描述为:

<bean id="projDataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
      destroy-method="close" lazy-init="true">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" ref="projDsUrl"/>
    <property name="username"
              value="#{props[T(daffel.digital.web.Constants).PROPS_DB_USERNAME]}"/>
    <property name="password" ref="decryptedPwd"/>
    <property name="initialSize" value="5"/>
    <property name="maxActive" value="10"/>
    <property name="maxIdle" value="5"/>
    <property name="minIdle" value="2"/>
    <property name="maxWait" value="10000"/>
    <property name="validationInterval" value="10000"/>
    <property name="validationQuery" value="select 1 from dual"/>
    <property name="testOnBorrow" value="true"/>
</bean>

此getOracleConnection()方法以try-with-resource方法调用:

try (Connection connection = DAOUtil.getOracleConnection();
         PreparedStatement stmt = connection.prepareStatement
                    ( GET_QUERY );
         ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            //do something
        }
    } catch (SQLException e) {
        String msg = "Query failed: " + GET_QUERY;
        LOG.error(msg, e);
        throw new DAOException(msg, e);
    }

有见识吗?

0 个答案:

没有答案