복붙노트

[SPRING] Spring 애플리케이션을 종료하면 데이터 소스의 JNDI 이름이 JDBC 컨텍스트에서 사라집니다.

SPRING

Spring 애플리케이션을 종료하면 데이터 소스의 JNDI 이름이 JDBC 컨텍스트에서 사라집니다.

내 Weblogic에서 Spring MVC 및 Spring Data JPA를 사용하여 웹 응용 프로그램을 설치하려고합니다. 섬기는 사람. 응용 프로그램을 처음으로 Weblogic 서버에 배포 할 때 응용 프로그램이 제대로 작동하지만 응용 프로그램을 중지하면 Weblogic 서버의 JNDI 트리에서 내 데이터 소스에 대한 jndi 이름 (jdbc / myDS)이 사라지고 응용 프로그램을 시작하려고 할 때 다시 다음 오류가 발생합니다.

Caused By: javax.naming.NameNotFoundException: Unable to resolve 'jdbc.myDS'. Resolved 'jdbc'; remaining name 'myDS'

JPAConfiguratation.java에서 시작할 때 다음을 설정합니다.

package mySpringApp.application;

import java.util.Properties;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * An application context Java configuration class. The usage of Java configuration
 * requires Spring Framework 3.0 or higher with following exceptions:
 * <ul>
 *     <li>@EnableWebMvc annotation requires Spring Framework 3.1</li>
 * </ul>
 */
@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
@ImportResource("classpath:applicationContext.xml")
@PropertySource("classpath:application.properties")
public class JPAConfiguration{

    private static final Logger logger = LoggerFactory.getLogger(JPAConfiguration.class);

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    @Resource
    private Environment environment;

    @Bean
    public DataSource dataSource() throws NamingException {    
        Context ctx = new InitialContext();
        String jndiName = "jdbc/myDS";
        DataSource dataSourceJNDINAME = (DataSource) ctx.lookup(jndiName);
        return dataSourceJNDINAME;
    ));


    @Bean
    public JpaTransactionManager transactionManager() throws ClassNotFoundException {
        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        try {
            entityManagerFactoryBean.setDataSource(dataSource());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Error setting datasource for entityManagerFactoryBean", e);
            logger.error(e.getMessage());
        }
        entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);

        Properties jpaProterties = new Properties();
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        entityManagerFactoryBean.setJpaProperties(jpaProterties);

        return entityManagerFactoryBean;
    }

웹 :

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <servlet>
        <servlet-name>MySpringApp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>mySpringApp.application</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>MySpringApp</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

응용 프로그램을 처음 종료 할 때 로그 출력 :

INFO  - onfigWebApplicationContext - Closing WebApplicationContext for namespace 'MySpringApp-servlet': startup date [Thu Oct 03 13:13:05 CEST 2013]; root of context hierarchy
DEBUG - DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
INFO  - DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1c51f5cb: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcesso
r,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.sprin
gframework.context.annotation.internalPersistenceAnnotationProcessor,webConfig,JPAConfiguration,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,homeController,firstController,buildController,
greetingController,repositoryBuildService,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.data.repository.core.sup
port.RepositoryInterfaceAwareBeanPostProcessor#1,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,viewControllerHandlerMapping,beanNameHandlerMapp
ing,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcConversionService,mvcValidator,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,messageSource,viewResolver,org.spr
ingframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.Http
RequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#1,buil
dRepository,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#2,org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration,org.springframework.transaction.config.internal
TransactionAdvisor,transactionAttributeSource,transactionInterceptor,dataSource,transactionManager,entityManagerFactoryBean,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#1,org.springframework.web.servlet.handler.S
impleUrlHandlerMapping#2,org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#1,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#3,org.springframework.data.repository.core.support.RepositoryInterface
AwareBeanPostProcessor#3]; root of factory hierarchy
DEBUG - DisposableBeanAdapter      - Invoking destroy() on bean with name 'org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration'
DEBUG - DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)': [(inner bean), buildRepository]
DEBUG - DisposableBeanAdapter      - Invoking destroy() on bean with name 'entityManagerFactoryBean'
INFO  - erEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'mySpringAppPersistenceUnit'
DEBUG - SessionFactoryImpl         - HHH000031: Closing
DEBUG - tityManagerFactoryRegistry - Remove: name=mySpringAppPersistenceUnit
DEBUG - DisposableBeanAdapter      - Invoking destroy method 'shutdown' on bean with name 'dataSource'
DEBUG - DisposableBeanAdapter      - Invoking destroy() on bean with name 'JPAConfiguration'
DEBUG - DisposableBeanAdapter      - Invoking destroy() on bean with name 'webConfig'
DEBUG - DisposableBeanAdapter      - Invoking destroy() on bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration'

나는 다음을 사용하고있다 :

어떻게 든 응용 프로그램의 종료를 수동으로 처리해야합니까? jndi 이름이 서버 컨텍스트에서 사라질 수있는 원인은 무엇입니까?

모든 도움을 주시면 대단히 감사하겠습니다!

해결법

  1. ==============================

    1.나는 똑같은 문제가 있었다. destroyMethod = "를 추가하면 나를 고칠 수 있습니다.

    나는 똑같은 문제가 있었다. destroyMethod = "를 추가하면 나를 고칠 수 있습니다.

    분명히 destroyMethod가 없다면 Spring은 destroy 메소드가 무엇인지 판단하려고 시도합니다. 이것은 분명히 데이터 소스가 닫히고 JNDI 키가 트리에서 제거되도록합니다. ""로 변경하면 destroyMethod를 찾지 않습니다.

    @Bean(destroyMethod = "")
    public DataSource dataSource() throws NamingException{
        Context context = new InitialContext();
        return (DataSource)context.lookup("jdbc.mydatasource");
    }
    
  2. from https://stackoverflow.com/questions/19158334/shutting-down-spring-application-makes-jndi-name-for-datasource-go-away-from-jdb by cc-by-sa and MIT license