Spring Cloud Starter Stream Source JDBC에 포함된 JDBC 드라이버

Java|2020. 1. 30. 19:01

Spring Cloud Data Flow(스프링 클라우드 데이터 플로우)에서 JDBC 소스를 사용해 하이브(Hive)에 연결하는 중에 JDBC 드라이버 클래스를 못 찾는다는 오류가 발생했다. spring.datasource.driver-class-name 옵션값은 제대로 넣었다. 심지어 문서에선 클래스 이름을 안 넣으면 spring.datasource.url에 입력한 URL로 알아서 판단한다고 돼 있다.

생각해 보니, 이 모듈이 모든 데이터베이스의 JDBC 드라이버를 가지고 있을 턱이 없다. 어떤 JDBC 드라이버를 내장하고 있는지 조사해봤더니 다음과 같다.

  • H2
  • MariaDB
  • PostgreSQL
  • Microsoft SQL Server

직접 확인하고 싶다면 스프링 클라우드 스트림 프로젝트의 코드 저장소에서 pom.xml 파일을 보면된다.

참고로 MySQL을 사용한다면 spring.datasource.driver-class-name 옵션을 다음과 같이 입력해 MariaDB 드라이버를 사용하면 된다.

  • spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

 

도움이 됐다면 공감 버튼을 클릭해 주세요. 감사합니다.

댓글()

AXBoot를 IntelliJ IDEA에서 처음 사용할 때 유의할 점

Java|2018. 3. 24. 15:15

AXBoot Initializer로 생성한 프로젝트를 IntelliJ IDEA에서 열고 실행하려고 하면, QMenu, QCommonCode 등의 JPA 도메인 클래스 관련 오류가 발생하면서 빌드가 실패한다.  

이럴 때는 "View > Tools Windows > Maven Projects" 메뉴를 이용해서 Maven 패널을 열고, Lifecycle 하위의 clean, package 골을 차례로 실행한다.  


이 오류는 Querydsl 관련 클래스가 없어서 발생하는데, 위의 과정을 통해서 생성하는 것이다.


EOF


태그 : axboot, idea, Spring

댓글()

AXBoot-WildFly 9을 사용할 때의 JWTSessionHandler 문제

Java|2018. 1. 9. 15:05

com.chequer.axboot.admin.utils.JWTSessionHandler는 javax.xml.bind.DatatypeConverter 클래스를 이용하여 BASE64 인코딩/디코딩을 수행합니다.
그런데 WildFly 9 버전의 경우에는 문제가 있습니다. WildFly 9은 JDK의 DatatypeConverter를 사용하는게 아니라 별도의 내장된 버전을 사용하기 때문입니다.

좀 더 정확하게는 wildfly-9.0.2.Final/modules/system/layers/base/javax/xml/bind/api/main/jboss-jaxb-api_2.2_spec-1.0.4.Final.jar 파일에 포함된 것을 사용합니다.

이 버전은 URL-safe 하지 않은 인코딩을 수행하기 때문에 쿠키를 이용한 로그인이 불가능한 심각한 문제가 발생합니다.

아래와 같이 Apache Commons Codec 프로젝트의 Base64 클래스를 사용하도록 수정하면 문제가 해결됩니다.

    import org.apache.commons.codec.binary.Base64;

    private String toBase64(byte[] content) {
        return Base64.encodeBase64URLSafeString(content);
    }

    private byte[] fromBase64(String content) {
        return Base64.decodeBase64(content);
    }

DatatypeConverter 를 써야하는 특별한 이유가 없다면 원본 소스도 이렇게 변경하는게 좋을 것 같습니다. 어차피 Commons Codec 프로젝트에는 이미 디펜던시가 있으니까요.


EOF


태그 : axboot, wildfly

댓글()

AXBoot Framework - war 파일 형태로 실행

Java|2017. 10. 14. 15:31

AXBoot Initialzr 로 생성한 프로젝트는 war 파일 형태로 바로 실행이 안된다.
안되길래 그냥 프로젝트 루트에서 $ mvn spring-boot:run 으로 실행했었는데, war 만 배포해서 실행할 일이 생겼다.

원인을 찾아보니 별일은 아니었다. 아래와 같이 Spring Boot Maven Plugin 을 pom.xml 의 plugins 부분에 추가하면 된다.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- ... -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.7.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

위 코드는 아래의 Spring Boot 공식 문서에서 가져온 것이다. 자세한 설명은 가서 보시길.

Spring Boot Maven plugin


EOF




태그 : axboot, maven

댓글()

WildFly (JBoss)가 자동 적용하는 라이브러리 배제 방법

Java|2017. 8. 7. 19:50

톰캣에서는 잘 돌아가던 애플리케이션이, WildFly에 배포해서 사용하려고 하면 로깅 부터 시작해서 여러가지 문제가 발생하는 경우가 있다. WildFly의 버전을 올리면 해결되는 경우도 있지만, 버전을 올릴 수 없는 경우에는 WildFly가 제공하는 디펜던시(dependencies)를 배제하여 애플리케이션의 자체 디펜던시를 사용하도록 조정해야 한다.

이를 위해서는 WEB-INF/jboss-deployment-structure.xml 파일을 만들고 아래와 같이 배제할 모듈을 명시하면 된다.

    <?xml version="1.0" encoding="UTF-8"?>
    <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
        <deployment>
            <exclude-subsystems>
                <subsystem name="logging" />
                <subsystem name="jaxrs" />
                <subsystem name="resteasy" />
            </exclude-subsystems>
            <!-- exclusions allow you to prevent the server from automatically adding some dependencies -->
            <exclusions>
                <module name="org.slf4j" />
                <module name="org.slf4j.impl" />
                <module name="org.slf4j.jcl-over-slf4j"/>
                <module name="org.apache.commons.logging"/>
                <module name="org.apache.log4j"/>
                <module name="javaee.api" />
                <module name="javax.xml.bind.api" />
                <module name="com.fasterxml.jackson.core.jackson-core" />
                <module name="com.fasterxml.jackson.core.jackson-databind" />
                <module name="com.fasterxml.jackson.core.jackson-annotations" />
                <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />
                <module name="org.jboss.resteasy.resteasy-jaxb-provider" />
                <module name="org.jboss.resteasy.resteasy-jettison-provider"/>
                <module name="org.jboss.resteasy.resteasy-jackson-provider"/>
                <module name="org.jboss.resteasy.resteasy-jackson2-provider" />
            </exclusions>
        </deployment>
    </jboss-deployment-structure>

배제할 모듈의 이름을 알아 내기 위해서는, $WILDFLY_HOME/modules/system/layers/base 디렉토리 하위의 각 디렉토리에서 module.xml 파일 내용을 확인하면 된다.


추가: 참고로 위의 설정 파일을 사용해서, WildFly( 9.0.2.Final 버전)에서 CONSOLE 로거로 Logback 로그를 출력하는 데에는 실패했습니다. 다만 FILE 로거로는 출력이 잘 됩니다.


EOF


태그 : java, wildfly

댓글()

Spring Boot : auto-configuration 그리고 debug

Java|2015. 4. 17. 13:39

Spring Boot 애플리케이션의 auto-configuration 정보를 확인하거나 DEBUG 레벨의 로그를 확인하려면 아래와 같이 --debug-Ddebug 옵션을 주면 됩니다.

$ java -jar myapp.jar --debug

그리고 문서에서는 확인이 안되지만 applicaton.properties 파일에, 값 없이 debug 키를 선언해도 됩니다(debug: 혹은 debug=).

debug:
spring.datasource.url: jdbc:hsqldb:file:D:/tmp/hsqldb/scratchdb
spring.jpa.show-sql: true
spring.jpa.generate-ddl: true
spring.jpa.hibernate.ddl-auto: create

이렇게 debug 옵션을 주면 auto-configuration 정보와 사용 중인 framework, library 등의 DEBUG 레벨 로그를 확인할 수 있습니다.

아래는 --debug 옵션과 함께 Spring Data JPA 앱의 테스트케이스를 실행했을 때의 콘솔 로그입니다.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.3.0.BUILD-SNAPSHOT)

2015-04-17 13:17:28.927  INFO 5124 --- [           main] c.i.rt.execution.junit.JUnitStarter      : Starting JUnitStarter on envy-i7 with PID 5124 (started by kyutae.park in D:\dev\repos\spring-boot-data-jpa-javaworld)
2015-04-17 13:17:28.928 DEBUG 5124 --- [           main] o.s.boot.SpringApplication               : Loading source class sample.data.jpa.SampleDataJpaApplication
2015-04-17 13:17:29.243 DEBUG 5124 --- [           main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application.yaml' resource not found

    ..............
    .... 중략 ....
    ..............

Hibernate: alter table tb_person_02837_cars add constraint FK_enugsq5f3484moat7h2ggrf1a foreign key (tb_person_02837_id) references tb_person_02837
2015-04-17 13:17:43.191  INFO 5124 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2015-04-17 13:17:45.352 DEBUG 5124 --- [           main] utoConfigurationReportLoggingInitializer : 


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   AopAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.context.annotation.EnableAspectJAutoProxy,org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
      - matched (OnPropertyCondition)

   AopAutoConfiguration.JdkDynamicAutoProxyConfiguration
      - matched (OnPropertyCondition)

   DataSourceAutoConfiguration
      - @ConditionalOnClass classes found: javax.sql.DataSource,org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

   DataSourceAutoConfiguration.DataSourceInitializerConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration
      - existing auto database detected (DataSourceAutoConfiguration.DataSourceAvailableCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#jdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#namedParameterJdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration.NonEmbeddedConfiguration
      - supported DataSource class found (DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition)
      - @ConditionalOnMissingBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourcePoolMetadataProvidersConfiguration.TomcatDataSourcePoolMetadataProviderConfiguration
      - @ConditionalOnClass classes found: org.apache.tomcat.jdbc.pool.DataSource (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration.TransactionManagementConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration; SearchStrategy: all) found no beans (OnBeanCondition)

   GenericCacheConfiguration
      - Automatic cache type (CacheCondition)

   HibernateJpaAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager (OnClassCondition)
      - found HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)

   HttpEncodingAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.web.filter.CharacterEncodingFilter (OnClassCondition)
      - matched (OnPropertyCondition)

   HttpEncodingAutoConfiguration#characterEncodingFilter
      - @ConditionalOnMissingBean (types: org.springframework.web.filter.CharacterEncodingFilter; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)

   HttpMessageConvertersAutoConfiguration#messageConverters
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration.StringHttpMessageConverterConfiguration
      - @ConditionalOnClass classes found: org.springframework.http.converter.StringHttpMessageConverter (OnClassCondition)

   HttpMessageConvertersAutoConfiguration.StringHttpMessageConverterConfiguration#stringHttpMessageConverter
      - @ConditionalOnMissingBean (types: org.springframework.http.converter.StringHttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)

   JacksonAutoConfiguration
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)

   JacksonAutoConfiguration.JacksonObjectMapperBuilderConfiguration
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper,org.springframework.http.converter.json.Jackson2ObjectMapperBuilder (OnClassCondition)

   JacksonAutoConfiguration.JacksonObjectMapperBuilderConfiguration#jacksonObjectMapperBuilder
      - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; SearchStrategy: all) found no beans (OnBeanCondition)

   JacksonAutoConfiguration.JacksonObjectMapperConfiguration
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper,org.springframework.http.converter.json.Jackson2ObjectMapperBuilder (OnClassCondition)

   JacksonAutoConfiguration.JacksonObjectMapperConfiguration#jacksonObjectMapper
      - @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found no beans (OnBeanCondition)

   JacksonHttpMessageConvertersConfiguration.MappingJackson2HttpMessageConverterConfiguration
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)
      - matched (OnPropertyCondition)
      - @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found the following [jacksonObjectMapper] (OnBeanCondition)

   JacksonHttpMessageConvertersConfiguration.MappingJackson2HttpMessageConverterConfiguration#mappingJackson2HttpMessageConverter
      - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactory
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; SearchStrategy: all) found no beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactoryBuilder
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder; SearchStrategy: all) found no beans (OnBeanCondition)

   JpaBaseConfiguration#jpaVendorAdapter
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.JpaVendorAdapter; SearchStrategy: all) found no beans (OnBeanCondition)

   JpaBaseConfiguration#transactionManager
      - @ConditionalOnMissingBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found no beans (OnBeanCondition)

   JtaAutoConfiguration
      - @ConditionalOnClass classes found: javax.transaction.Transaction (OnClassCondition)
      - matched (OnPropertyCondition)

   MultipartAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver,javax.servlet.MultipartConfigElement (OnClassCondition)
      - matched (OnPropertyCondition)

   MultipartAutoConfiguration#multipartConfigElement
      - @ConditionalOnMissingBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found no beans (OnBeanCondition)

   MultipartAutoConfiguration#multipartResolver
      - @ConditionalOnMissingBean (types: org.springframework.web.multipart.MultipartResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   NoOpCacheConfiguration
      - Automatic cache type (CacheCondition)

   PersistenceExceptionTranslationAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor (OnClassCondition)

   PersistenceExceptionTranslationAutoConfiguration#persistenceExceptionTranslationPostProcessor
      - @ConditionalOnMissingBean (types: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; SearchStrategy: all) found no beans (OnBeanCondition)
      - matched (OnPropertyCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

   RedisCacheConfiguration
      - Automatic cache type (CacheCondition)

   SimpleCacheConfiguration
      - Automatic cache type (CacheCondition)

   TransactionAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.transaction.support.TransactionTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
      - @ConditionalOnSingleCandidate (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found a primary candidate amongst the following [transactionManager] (OnBeanCondition)

   TransactionAutoConfiguration#transactionTemplate
      - @ConditionalOnMissingBean (types: org.springframework.transaction.support.TransactionTemplate; SearchStrategy: all) found no beans (OnBeanCondition)

   WebSocketAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,javax.websocket.server.ServerContainer (OnClassCondition)

   WebSocketAutoConfiguration.TomcatWebSocketConfiguration
      - @ConditionalOnClass classes found: org.apache.catalina.startup.Tomcat,org.apache.tomcat.websocket.server.WsSci (OnClassCondition)

   WebSocketAutoConfiguration.TomcatWebSocketConfiguration#websocketContainerCustomizer
      - @ConditionalOnMissingBean (names: websocketContainerCustomizer; SearchStrategy: all) found no beans (OnBeanCondition)


Negative matches:
-----------------

   ActiveMQAutoConfiguration
      - required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.apache.activemq.ActiveMQConnectionFactory (OnClassCondition)

   AopAutoConfiguration.CglibAutoProxyConfiguration
      - @ConditionalOnProperty missing required properties spring.aop.proxy-target-class  (OnPropertyCondition)

   AtomikosJtaConfiguration
      - required @ConditionalOnClass classes not found: com.atomikos.icatch.jta.UserTransactionManager (OnClassCondition)

   BatchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)

   BitronixJtaConfiguration
      - required @ConditionalOnClass classes not found: bitronix.tm.jndi.BitronixContext (OnClassCondition)

   CacheAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.cache.CacheManager (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.cache.interceptor.CacheAspectSupport; SearchStrategy: all) found no beans (OnBeanCondition)

   CloudAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.cloud.config.java.CloudScanConfiguration (OnClassCondition)

   DataSourceAutoConfiguration.EmbeddedConfiguration
      - existing non-embedded database detected (DataSourceAutoConfiguration.EmbeddedDataSourceCondition)

   DataSourceAutoConfiguration.TomcatDataSourceJmxConfiguration
      - @ConditionalOnClass classes found: org.apache.tomcat.jdbc.pool.DataSourceProxy (OnClassCondition)
      - existing auto database detected (DataSourceAutoConfiguration.DataSourceAvailableCondition)
      - @ConditionalOnProperty missing required properties spring.datasource.jmx-enabled  (OnPropertyCondition)

   DataSourcePoolMetadataProvidersConfiguration.CommonsDbcpPoolDataSourceMetadataProviderConfiguration
      - required @ConditionalOnClass classes not found: org.apache.commons.dbcp.BasicDataSource (OnClassCondition)

   DataSourcePoolMetadataProvidersConfiguration.HikariPoolDataSourceMetadataProviderConfiguration
      - required @ConditionalOnClass classes not found: com.zaxxer.hikari.HikariDataSource (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration#transactionManager
      - @ConditionalOnMissingBean (names: transactionManager; SearchStrategy: all) found the following [transactionManager] (OnBeanCondition)

   DeviceDelegatingViewResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver (OnClassCondition)

   DeviceResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

   DispatcherServletAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
      - not a web application (OnWebApplicationCondition)

   EhCacheCacheConfiguration
      - required @ConditionalOnClass classes not found: net.sf.ehcache.Cache,org.springframework.cache.ehcache.EhCacheCacheManager (OnClassCondition)

   ElasticsearchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.client.TransportClientFactoryBean,org.springframework.data.elasticsearch.client.NodeClientFactoryBean (OnClassCondition)

   ElasticsearchDataAutoConfiguration
      - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.core.ElasticsearchTemplate (OnClassCondition)

   ElasticsearchRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.repository.ElasticsearchRepository (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration
      - not a web application (OnWebApplicationCondition)

   ErrorMvcAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
      - not a web application (OnWebApplicationCondition)

   FacebookAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.social.config.annotation.SocialConfigurerAdapter,org.springframework.social.facebook.connect.FacebookConnectionFactory (OnClassCondition)

   FallbackWebSecurityAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.security.config.annotation.web.configuration.EnableWebSecurity (OnClassCondition)

   FlywayAutoConfiguration
      - required @ConditionalOnClass classes not found: org.flywaydb.core.Flyway (OnClassCondition)

   FreeMarkerAutoConfiguration
      - required @ConditionalOnClass classes not found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory (OnClassCondition)

   GroovyTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: groovy.text.markup.MarkupTemplateEngine (OnClassCondition)

   GsonAutoConfiguration
      - required @ConditionalOnClass classes not found: com.google.gson.Gson (OnClassCondition)

   GsonHttpMessageConvertersConfiguration
      - required @ConditionalOnClass classes not found: com.google.gson.Gson (OnClassCondition)

   GuavaCacheConfiguration
      - required @ConditionalOnClass classes not found: com.google.common.cache.CacheBuilder,org.springframework.cache.guava.GuavaCacheManager (OnClassCondition)

   GzipFilterAutoConfiguration
      - required @ConditionalOnClass classes not found: org.eclipse.jetty.servlets.GzipFilter (OnClassCondition)

   HazelcastCacheConfiguration
      - required @ConditionalOnClass classes not found: com.hazelcast.core.HazelcastInstance,com.hazelcast.spring.cache.HazelcastCacheManager (OnClassCondition)

   HornetQAutoConfiguration
      - required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.hornetq.api.jms.HornetQJMSClient (OnClassCondition)

   HypermediaAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.hateoas.Resource,org.springframework.plugin.core.Plugin (OnClassCondition)

   IntegrationAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.integration.config.EnableIntegration (OnClassCondition)

   JCacheCacheConfiguration
      - required @ConditionalOnClass classes not found: javax.cache.Caching,org.springframework.cache.jcache.JCacheCacheManager (OnClassCondition)

   JacksonAutoConfiguration.JodaDateTimeJacksonConfiguration
      - required @ConditionalOnClass classes not found: org.joda.time.DateTime,com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer,com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat (OnClassCondition)

   JacksonHttpMessageConvertersConfiguration.MappingJackson2XmlHttpMessageConverterConfiguration
      - required @ConditionalOnClass classes not found: com.fasterxml.jackson.dataformat.xml.XmlMapper (OnClassCondition)

   JerseyAutoConfiguration
      - required @ConditionalOnClass classes not found: org.glassfish.jersey.server.spring.SpringComponentProvider (OnClassCondition)

   JmsAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate (OnClassCondition)

   JmxAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
      - @ConditionalOnProperty expected 'true' for properties spring.jmx.enabled (OnPropertyCondition)

   JndiConnectionFactoryAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate (OnClassCondition)

   JndiDataSourceAutoConfiguration
      - @ConditionalOnClass classes found: javax.sql.DataSource,org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
      - @ConditionalOnProperty missing required properties spring.datasource.jndi-name  (OnPropertyCondition)

   JndiJtaConfiguration
      - @ConditionalOnClass classes found: org.springframework.transaction.jta.JtaTransactionManager (OnClassCondition)
      - JNDI environment is not available (OnJndiCondition)

   JpaBaseConfiguration.JpaWebConfiguration
      - @ConditionalOnClass classes found: org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
      - not a web application (OnWebApplicationCondition)

   JpaRepositoriesAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
      - matched (OnPropertyCondition)
      - @ConditionalOnMissingBean (types: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean,org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension; SearchStrategy: all) found the following [&personRepository, &reviewRepository, &cityRepository, &hotelRepository, &carRepository, org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension#0] (OnBeanCondition)

   LinkedInAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.social.config.annotation.SocialConfigurerAdapter,org.springframework.social.linkedin.connect.LinkedInConnectionFactory (OnClassCondition)

   LiquibaseAutoConfiguration
      - required @ConditionalOnClass classes not found: liquibase.integration.spring.SpringLiquibase (OnClassCondition)

   MailSenderAutoConfiguration
      - required @ConditionalOnClass classes not found: javax.mail.internet.MimeMessage (OnClassCondition)

   MessageSourceAutoConfiguration
      - No bundle found for spring.messages.basename: messages (MessageSourceAutoConfiguration.ResourceBundleCondition)

   MongoAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo (OnClassCondition)

   MongoDataAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.core.MongoTemplate (OnClassCondition)

   MongoRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

   MustacheAutoConfiguration
      - required @ConditionalOnClass classes not found: com.samskivert.mustache.Mustache (OnClassCondition)

   RabbitAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

   ReactorAutoConfiguration
      - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor,reactor.core.Environment (OnClassCondition)

   RedisAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.redis.connection.jedis.JedisConnection,org.springframework.data.redis.core.RedisOperations,redis.clients.jedis.Jedis (OnClassCondition)

   RepositoryRestMvcAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration (OnClassCondition)

   SecurityAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.security.authentication.AuthenticationManager,org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter (OnClassCondition)

   SendGridAutoConfiguration
      - required @ConditionalOnClass classes not found: com.sendgrid.SendGrid (OnClassCondition)

   ServerPropertiesAutoConfiguration
      - not a web application (OnWebApplicationCondition)

   SitePreferenceAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor,org.springframework.mobile.device.site.SitePreferenceHandlerMethodArgumentResolver (OnClassCondition)

   SocialWebAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.social.connect.web.ConnectController,org.springframework.social.config.annotation.SocialConfigurerAdapter (OnClassCondition)

   SolrAutoConfiguration
      - required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.impl.HttpSolrServer,org.apache.solr.client.solrj.impl.CloudSolrServer (OnClassCondition)

   SolrRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.SolrServer,org.springframework.data.solr.repository.SolrRepository (OnClassCondition)

   SpringDataWebAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.data.web.PageableHandlerMethodArgumentResolver,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
      - not a web application (OnWebApplicationCondition)

   ThymeleafAutoConfiguration
      - required @ConditionalOnClass classes not found: org.thymeleaf.spring4.SpringTemplateEngine (OnClassCondition)

   TwitterAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.social.config.annotation.SocialConfigurerAdapter,org.springframework.social.twitter.connect.TwitterConnectionFactory (OnClassCondition)

   VelocityAutoConfiguration
      - required @ConditionalOnClass classes not found: org.apache.velocity.app.VelocityEngine,org.springframework.ui.velocity.VelocityEngineFactory (OnClassCondition)

   WebMvcAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
      - not a web application (OnWebApplicationCondition)

   WebSocketAutoConfiguration.JettyWebSocketConfiguration
      - required @ConditionalOnClass classes not found: org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer (OnClassCondition)

   WebSocketAutoConfiguration.UndertowWebSocketConfiguration
      - required @ConditionalOnClass classes not found: io.undertow.websockets.jsr.Bootstrap (OnClassCondition)

   XADataSourceAutoConfiguration
      - @ConditionalOnClass classes found: javax.sql.DataSource,javax.transaction.TransactionManager,org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.boot.jta.XADataSourceWrapper; SearchStrategy: all) found no beans (OnBeanCondition)


Exclusions:
-----------

    None



2015-04-17 13:17:45.388  INFO 5124 --- [           main] c.i.rt.execution.junit.JUnitStarter      : Started JUnitStarter in 23.914 seconds (JVM running for 45.382)
2015-04-17 13:17:45.461 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select count(city0_.id) as col_0_0_ from city city0_
Hibernate: select count(city0_.id) as col_0_0_ from city city0_
2015-04-17 13:17:45.468 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select city0_.id as id1_0_, city0_.country as country2_0_, city0_.map as map3_0_, city0_.name as name4_0_, city0_.state as state5_0_ from city city0_ order by city0_.name asc limit ?
Hibernate: select city0_.id as id1_0_, city0_.country as country2_0_, city0_.map as map3_0_, city0_.name as name4_0_, city0_.state as state5_0_ from city city0_ order by city0_.name asc limit ?
2015-04-17 13:17:45.490 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select count(hotel0_.id) as col_0_0_ from hotel hotel0_ left outer join review reviews1_ on hotel0_.id=reviews1_.hotel_id where hotel0_.city_id=? group by hotel0_.id
Hibernate: select count(hotel0_.id) as col_0_0_ from hotel hotel0_ left outer join review reviews1_ on hotel0_.id=reviews1_.hotel_id where hotel0_.city_id=? group by hotel0_.id
2015-04-17 13:17:45.502 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select hotel0_.city_id as col_0_0_, hotel0_.name as col_1_0_, avg(cast(reviews1_.rating as double)) as col_2_0_ from hotel hotel0_ left outer join review reviews1_ on hotel0_.id=reviews1_.hotel_id inner join city city2_ on hotel0_.city_id=city2_.id where hotel0_.city_id=? group by hotel0_.id order by hotel0_.name asc limit ?
Hibernate: select hotel0_.city_id as col_0_0_, hotel0_.name as col_1_0_, avg(cast(reviews1_.rating as double)) as col_2_0_ from hotel hotel0_ left outer join review reviews1_ on hotel0_.id=reviews1_.hotel_id inner join city city2_ on hotel0_.city_id=city2_.id where hotel0_.city_id=? group by hotel0_.id order by hotel0_.name asc limit ?
2015-04-17 13:17:45.515 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select city0_.id as id1_0_0_, city0_.country as country2_0_0_, city0_.map as map3_0_0_, city0_.name as name4_0_0_, city0_.state as state5_0_0_ from city city0_ where city0_.id=?
Hibernate: select city0_.id as id1_0_0_, city0_.country as country2_0_0_, city0_.map as map3_0_0_, city0_.name as name4_0_0_, city0_.state as state5_0_0_ from city city0_ where city0_.id=?
2015-04-17 13:17:45.520  WARN 5124 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Warning Code: -1003, SQLState: 01003
2015-04-17 13:17:45.520  WARN 5124 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : warning: null value eliminated in set function
2015-04-17 13:17:45.528 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select hotel0_.id as id1_1_, hotel0_.address as address2_1_, hotel0_.city_id as city_id5_1_, hotel0_.name as name3_1_, hotel0_.zip as zip4_1_ from hotel hotel0_ where hotel0_.city_id=? and hotel0_.name=?
Hibernate: select hotel0_.id as id1_1_, hotel0_.address as address2_1_, hotel0_.city_id as city_id5_1_, hotel0_.name as name3_1_, hotel0_.zip as zip4_1_ from hotel hotel0_ where hotel0_.city_id=? and hotel0_.name=?
2015-04-17 13:17:45.530 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select city0_.id as id1_0_0_, city0_.country as country2_0_0_, city0_.map as map3_0_0_, city0_.name as name4_0_0_, city0_.state as state5_0_0_ from city city0_ where city0_.id=?
Hibernate: select city0_.id as id1_0_0_, city0_.country as country2_0_0_, city0_.map as map3_0_0_, city0_.name as name4_0_0_, city0_.state as state5_0_0_ from city city0_ where city0_.id=?
2015-04-17 13:17:45.537 DEBUG 5124 --- [           main] org.hibernate.SQL                        : select review0_.rating as col_0_0_, count(review0_.id) as col_1_0_ from review review0_ where review0_.hotel_id=? group by review0_.rating order by review0_.rating DESC
Hibernate: select review0_.rating as col_0_0_, count(review0_.id) as col_1_0_ from review review0_ where review0_.hotel_id=? group by review0_.rating order by review0_.rating DESC
2015-04-17 13:17:45.543  INFO 5124 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7050ad86: startup date [Fri Apr 17 13:17:29 GMT+09:00 2015]; root of context hierarchy
2015-04-17 13:17:45.548  INFO 5124 --- [       Thread-1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

Process finished with exit code 0

조금 길지만 auto-configuration에 관한 내용을 찬찬히 읽어 보면 어떻게 앱이 자동 설정되었는지 확인할 수 있습니다.

EOF

댓글()

Spring Data JPA - LazyInitializationException

Java|2015. 4. 14. 10:00

개요

요즘 Spring Boot 저장소에 있는 Spring Data JPA 샘플 프로젝트를 살펴 보고 있습니다.

테스트 코드를 작성하면서 하나하나 파악하고 있는데, OneToMany로 엮인 다른 엔티티의 목록을 가져오려고 하면 아래와 같은 오류가 발생합니다.

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: kr.co.javaworld.jpa.domain.Person.cars, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:155)
    at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:278)
    at org.hamcrest.collection.IsCollectionWithSize.featureValueOf(IsCollectionWithSize.java:21)
    at org.hamcrest.collection.IsCollectionWithSize.featureValueOf(IsCollectionWithSize.java:14)
    at org.hamcrest.FeatureMatcher.matchesSafely(FeatureMatcher.java:40)
    at org.hamcrest.TypeSafeDiagnosingMatcher.matches(TypeSafeDiagnosingMatcher.java:55)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
    at org.junit.Assert.assertThat(Assert.java:956)
    at org.junit.Assert.assertThat(Assert.java:923)
    at kr.co.javaworld.jpa.service.PersonRepositoryIntegrationTests.testFindCars(PersonRepositoryIntegrationTests.java:46)
    ..............
    .... 중략 ....
    ..............
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

늦은 초기화(Lazy initialization)에 관련된 예외 상황인데, 이에 대한 해결 방법을 정리해 봅니다.

예외가 발생하는 코드

아래의 테스트 코드를 실행하던 중 예외가 발생했습니다. testFindCars 메소드는 Person 객체를 하나 찾은 후, 다시 그 Person이 가진 Car 목록을 조회하는 테스트 코드입니다.

Person.getCars() 호출 후 목록(cars)의 크기를 얻으려고 하니까(assertThat(cars, hasSize(4))) 오류가 발생했습니다.

package kr.co.javaworld.jpa.service;

import kr.co.javaworld.jpa.domain.Car;
import kr.co.javaworld.jpa.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import sample.data.jpa.SampleDataJpaApplication;

import javax.transaction.Transactional;
import java.util.List;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)
public class PersonRepositoryIntegrationTests {

    @Autowired
    PersonRepository repository;

    ..............
    .... 중략 ....
    ..............

    @Test
    public void testFindCars() {
        Person person = repository.findOne(1L);
        List<Car> cars = person.getCars();

        assertThat(cars, hasSize(4));
        assertThat(cars.get(0).getName(), is("Mercedes"));
    }
}

Person 엔티티의 코드입니다.
cars@OneToMany annotation이 붙어있을 뿐 특별한 점은 없습니다.

package kr.co.javaworld.jpa.domain;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "TB_PERSON_02837")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "PERSON_NAME", length = 100, unique = true, nullable = false)
    private String name;

    @OneToMany
    private List<Car> cars;

    ..............
    .... 중략 ....
    ..............

}

해결 방법

@OneToMany로 엮을 경우 JPA는 늦은 초기화를 통해 Personcars 목록을 가져오는게 기본 설정입니다. 즉, 위 코드의 @OneToMany annotation 선언은 @OneToMany(fetch = FetchType.LAZY)로 대체해도 동일합니다.

따라서 해결 방법은 간단합니다. 패치 타입을 FetchType.EAGER로 변경하여 늦은 초기화 대신 이른 초기화(Eager initialization)를 사용하면 됩니다.

아래 코드와 같이 @OneToMany(fetch = FetchType.EAGER)로 annotation 선언을 변경해 주면 오류가 사라집니다.

package kr.co.javaworld.jpa.domain;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "TB_PERSON_02837")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "PERSON_NAME", length = 100, unique = true, nullable = false)
    private String name;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Car> cars;

    ..............
    .... 중략 ....
    ..............

}

다른 해결 방법

앞서의 해결 방법은 People 엔티티를 얻어 올 때는 언제나 Car 목록도 함께 가져오도록 강제합니다. 따라서 가끔씩만 Car 목록이 필요하다면 불필요한 메모리 낭비나 서버 성능 저하 등의 문제가 발생할 수 있습니다.

늦은 초기화를 사용하면서도 문제를 해결하려면 아래와 같이 트랜잭션을 Person.getCar() 호출 후 관련 동작을 완료할 때까지 유지하면 됩니다.

아래에서는 testFindCars 메소드에 @Transactional annotation을 붙여서 메소드 전체를 하나의 트랜잭션으로 감쌌습니다.

실무에서는 서비스 클래스의 메소드 단위로 트랜잭션을 잡아 주거나, 뷰 단의 서블릿 필터에서 UserTransaction을 이용하여 요청 단위로 트랜잭션을 처리하는 방법을 사용하면 됩니다.

package kr.co.javaworld.jpa.service;

import kr.co.javaworld.jpa.domain.Car;
import kr.co.javaworld.jpa.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import sample.data.jpa.SampleDataJpaApplication;

import javax.transaction.Transactional;
import java.util.List;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)
public class PersonRepositoryIntegrationTests {

    @Autowired
    PersonRepository repository;

    ..............
    .... 중략 ....
    ..............

    @Test
    @Transactional
    public void testFindCars() {
        Person person = repository.findOne(1L);
        List<Car> cars = person.getCars();

        assertThat(cars, hasSize(4));
        assertThat(cars.get(0).getName(), is("Mercedes"));
    }
}

EOF

태그 : jpa, Spring

댓글()
  1. 준티 2016.10.05 12:34 댓글주소  수정/삭제  댓글쓰기

    감사합니다 !

  2. ryan 2018.04.02 18:58 댓글주소  수정/삭제  댓글쓰기

    이에러 잡는데 오늘 하루 걸렷네요. 감사합니다.

  3. 우왓 2018.07.09 09:39 댓글주소  수정/삭제  댓글쓰기

    우왕 해결되었어요 감사합니다!

Spring Shell Command 구현

Java|2015. 1. 7. 22:16

개요

HelloWorldCommands 클래스를 통해서 Spring Shell 커맨드 구현 방법을 살펴 보겠습니다.

Marker interface

HelloWorldCommands는 org.springframework.shell.core.CommandMarker 인터페이스를 구현하고 있습니다.

@Component
public class HelloWorldCommands implements CommandMarker {

}

CommandMarker는 마커 인터페이스라서 커맨드 구현체라는 것을 알려주기 위해서 implements 할 뿐입니다. 따라서 구현할 메소드는 없습니다.
@Component annotation은 component-scan을 통해 bean으로 등록되라고 붙여 줬습니다.

CLI Annotation

HelloWorldCommands는 모두 3개의 annotation을 사용하여 쉘에서의 동작을 제어합니다.

CliAvailabilityIndicator

어떤 커맨드가 쉘에서 사용 가능한지를 알려주기 위해서 사용합니다. 이 annotation은 boolean 값을 반환하는 메소드에 붙이며, 이 메소드는 annotation에 명시한 커맨드의 사용 가능 여부를 반환합니다.
HelloWorldCommands에서는 hw simple, hw complex, hw enum 커맨드의 사용 가능 여부를 알려 주기 위해서 사용하였습니다.

    private boolean simpleCommandExecuted = false;

    @CliAvailabilityIndicator({"hw simple"})
    public boolean isSimpleAvailable() {
        //always available
        return true;
    }

    @CliAvailabilityIndicator({"hw complex", "hw enum"})
    public boolean isComplexAvailable() {
        if (simpleCommandExecuted) {
            return true;
        } else {
            return false;
        }
    }

위에서 isSimpleAvailable() 메소드는 언제나 true를 반환하여, hw simple 커맨드가 언제나 사용 가능하다고 알려주고 있습니다.
isComplexAvailable 메소드는 simpleCommandExecuted 변수의 상태에 따라서 hw complex, hw enum 커맨드의 사용 가능 여부를 알려줍니다.

태그 : Shell, Spring

댓글()

Spring Shell 소개

Java|2015. 1. 2. 11:17

소개

스프링 프로그래밍 모델을 기반으로 손쉽게 커맨드라인 애플리케이션(interactive shell)을 만들 수 있도록 도와주는 프로젝트입니다.

홈페이지(GitHub)

https://github.com/spring-projects/spring-shell

샘플 애플리케이션

Spring Shell은 샘플 애플리케이션을 제공합니다. HelloWorld 애플리케이션은 부트스트랩(Bootstrap)/커맨드(Command)/베너(Banner)/프롬프트(Prompt)의 기본 구현 방법을 보여줍니다.
샘플을 통해 Spring Shell을 이해하는게 효과적이기 때문에 이를 통해 Spring Shell 사용 방법을 하나하나 설명토록 하겠습니다.

Clone

먼저 Spring Shell 프로젝트를 Clone합니다.

~$ git clone git@github.com:spring-projects/spring-shell.git

빌드 및 실행

Clone이 완료되면, samples/helloworld 디렉토리로 이동한 후 ./gradlew installApp 명령으로 HelloWorld 샘플을 빌드합니다.

~$ cd spring-shell/samples/helloworld
~/spring-shell/samples/helloworld$ ./gradlew installApp
:compileJava
:processResources
:classes
:jar
:startScripts
:installApp

BUILD SUCCESSFUL

./gradlew -q run 명령 혹은 build/install/helloworld/bin/helloworld 스크립트를 실행하면 HelloWorld 샘플을 실행할 수 있습니다.
build/install/helloworld 디렉토리에는 실행 스크립트(bin/helloworld)와 의존 라이브러리(lib/*.jar)가 모두 들어 있기 때문에 이 디렉토리만 배포하면 누구든 이 애플리케이션을 사용할 수 있게 됩니다.
사실 실행만 원한다면 빌드 없이 ./gradlew -q run 명령만 사용해도 됩니다.

~$ cd spring-shell/samples/helloworld
~/spring-shell/samples/helloworld$ ./gradlew -q run
=======================================
*                                     *
*            HelloWorld               *
*                                     *
=======================================
Version:1.2.3
Welcome to HelloWorld CLI
hw-shell>

구현 상세

HelloWorld는 아래 5개의 클래스로 구현되어 있었습니다.

  • org.springframework.shell.samples.helloworld.Main
  • org.springframework.shell.samples.helloworld.commands.HelloWorldCommands
  • org.springframework.shell.samples.helloworld.commands.MyBannerProvider
  • org.springframework.shell.samples.helloworld.commands.MyHistoryFileNameProvider
  • org.springframework.shell.samples.helloworld.commands.MyPromptProvider

Main 클래스는 org.springframework.shell.Bootstrap 클래스의 main 메소드를 호출하여 애플리케이션을 실행합니다.

    /**
     * Main class that delegates to Spring Shell's Bootstrap class in order to simplify debugging inside an IDE
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        Bootstrap.main(args);
    }

이 때 "/META-INF/spring/spring-shell-plugin.xml" 파일을 이용해 ApplicationContext를 생성합니다. spring-shell-plugin.xml 파일은 다음과 같이 단촐합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.springframework.shell.samples.helloworld.commands" />

</beans>

component-scan을 통해 bean을 찾기 때문에 Main 이외의 모든 클래스는 Component annotation을 달고 있습니다.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyPromptProvider extends DefaultPromptProvider {

    @Override
    public String getPrompt() {
        return "hw-shell>";
    }


    @Override
    public String getProviderName() {
        return "My prompt provider";
    }

}

위의 MyPromptProvider 클래스는 Order annotation 또한 달고 있는데, 이는 혹 클래스 패스에 다른 plugin이 Provider(Banner/Prompt/HistoryFileName) 구현체를 가지고 있더라도 내가 구현한 Provider를 우선하도록(Ordered.HIGHEST_PRECEDENCE) 합니다. Provider에 대해서는 곧 설명합니다.

Provider는 Spring Shell이 쉘을 커스터마이징 할 수 있도록 제공하는 확장 포인트로 모두 org.springframework.shell.plugin.NamedProvider 인터페이스를 상속한 인터페이스입니다.

HelloWorld가 사용하는 구현 클래스는 모두 Spring Shell이 제공하는 각 Provider의 기본 구현체(DefaultXXXProvider)를 상속하고 있습니다. HelloWorld는 총 3개의 Provider 구현 클래스를 가지고 있습니다.

  • MyBannerProvider는 이름이 알려주듯이 배너 정보를 담고 있는데, 이외에 버전정보(getVersion()), 환영 메시지(getWelcomeMessage()) 또한 제공합니다.
  • MyPromptProvider는 프롬프트 모양을 정의(getPrompt())합니다.
  • MyHistoryFileNameProvider는 쉘의 동작 히스토리를 담을 로그파일 이름(my.log)을 정의합니다.

MyHistoryFileNameProvider의 코드는 다음과 같습니다.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyHistoryFileNameProvider extends DefaultHistoryFileNameProvider {

    public String getHistoryFileName() {
        return "my.log";
    }

    @Override
    public String getProviderName() {
        return "My history file name provider";
    }

}

MyBannerProvider의 코드는 다음과 같습니다.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyBannerProvider extends DefaultBannerProvider  {

    public String getBanner() {
        StringBuffer buf = new StringBuffer();
        buf.append("=======================================" + OsUtils.LINE_SEPARATOR);
        buf.append("*                                     *"+ OsUtils.LINE_SEPARATOR);
        buf.append("*            HelloWorld               *" +OsUtils.LINE_SEPARATOR);
        buf.append("*                                     *"+ OsUtils.LINE_SEPARATOR);
        buf.append("=======================================" + OsUtils.LINE_SEPARATOR);
        buf.append("Version:" + this.getVersion());
        return buf.toString();
    }

    public String getVersion() {
        return "1.2.3";
    }

    public String getWelcomeMessage() {
        return "Welcome to HelloWorld CLI";
    }

    @Override
    public String getProviderName() {
        return "Hello World Banner";
    }
}

HelloWorld를 실행하면 배너와 버전 정보, 환영 메시지가 출력된 후 hw-shell> 프롬프트 옆에서 커서가 깜빡입니다.
앞에서 설명했듯이 이 때 출력되는 모든 정보는 MyBannerProvider가 제공하며, hw-shell> 프롬프트는 MyPromptProvider에서 정의하고 있습니다.
그리고 HelloWorld를 실행한 디렉토리를 탐색해 보면 MyHistoryFileNameProvider에서 정의한 my.log 파일이 생성된 것을 확인할 수 있습니다.

=======================================
*                                     *
*            HelloWorld               *
*                                     *
=======================================
Version:1.2.3
Welcome to HelloWorld CLI
hw-shell>

지금까지 Spring Shell에 대한 기본적인 내용과 Provider에 대해 알아봤습니다.
가장 중요한 커맨드 클래스에 대해서는 따로 글을 올리겠습니다.

태그 : Shell, Spring

댓글()

logback.xml - No grammar constraints (DTD or XML Schema) referenced in the document

Java|2012. 5. 10. 14:46

Logback은 DTD나 Schema를 제공하지 않는다.

문제는 이클립스에서 이에 대한 Warning을 한다는 것이다. 없는데 어쩌라고...

 

이럴 때는 아래와 같이 <!DOCTYPE xml>을 추가해 주면 경고가 사라진다.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>


혹은, 이클립스의 Window - Preference > XML - XML Files - Validation 메뉴에서 'No grammar specified' 항목의 값을 'Ignore'로 바꾸고 Validation을 실행해 보면 경고가 사라진다. 

태그 : logback

댓글()

Spring MVC의 CommonsMultipartResolver를 사용하여 업로드한 임시파일은 지워질까?

Java|2010. 2. 23. 23:30

Spring MVC는 Commons FileUpload 패키지를 이용한 파일 업로드를 지원한다.


아무 생각 없이 사용하고 있다가 문득 FileUpload를 Spring 없이 사용할 때는 FileCleanerCleanup 리스너를 web.xml에 등록해서 temporary 파일을 자동으로 삭제하게 한다는게 기억났다.


아차! 지금이라도 등록해 줘야하는건가? 하는 생각에 확인차 서버의 temporary 경로를 살펴봤다.

그런데 이상하게도 파일 업로드 후에 남아 있었어야할 임시 파일이 하나도 없었다.


CommonsMultipartResolver가 뭔가 알아서 지우는건가 해서 뒤져봐도 관련 코드는 없었다.

이해가 안가서 좀 더 뒤지다가 결국 DispatcherServlet에서 삭제 코드를 찾았다. doDispatch 메서드의 finally 절에 cleanupMultipart 메서드를 호출하는 부분이 있었던 것이다.

public class DispatcherServlet extends FrameworkServlet {


    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ......

        try {

            ......

        finally {

            // Clean up any resources used by a multipart request.

            if (processedRequest != request) {

                cleanupMultipart(processedRequest);

            }


            // Reset thread-bound context.

            RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);

            LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);


            // Clear request attributes.

            requestAttributes.requestCompleted();

            if (logger.isTraceEnabled()) {

                logger.trace("Cleared thread-bound request context: " + request);

            }

        }

    }


    /**

     * Clean up any resources used by the given multipart request (if any).

     * @param request current HTTP request

     * @see MultipartResolver#cleanupMultipart

     */

    protected void cleanupMultipart(HttpServletRequest request) {

        if (request instanceof MultipartHttpServletRequest) {

            this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) request);

        }

    }

    ......

}




태그 : multipart, mvc, Spring

댓글()

Commons FileUpload 1.2 버젼의 boundary 오류

Java|2008. 1. 4. 10:45
Commons FileUpload 1.2 버젼을 사용하여 ActiveX 업로드 컨트롤을 테스트 하던 중, "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"라는 에러 메시지를 보게 되었습니다. Commons FileUpload 사이트의 가이드를 따라 하던 중이라 별로 잘못한 건 없어보였는데 말이죠.

NetBeans에 포함된 HTTP Monitor의 도움을 받아(FiddlerHttpWatch는 ActiveX에서 발생하는 HTTP 통신을 볼 수 없더군요) HTTP Header 정보를 살펴보니 content-type은 아래와 같은 형식이었습니다.

multipart/form-data, boundary=ZYDa6MZ62846kJOUYu9kybvA750KGm3r

문제는 글자를 하나하나 아무리 뜯어봐도 boundary를 못찾을 이유가 없어 보인다는 겁니다.
결국 Commons FileUpload의 boundary 관련 소스를 다 뒤져보기에 이르렀는데... 이놈은 boundary 구분자로 세미콜론(;)을 사용하더군요. 제가 사용하는 업로드 컨트롤은 구분자로 쉼표(,)를 사용하고 있으니까 당연히 boundary를 못찾죠.
이걸 어떻게 해야하나... "직접 소스를 고칠까?" "이슈 등록을?" 등등의 고민을 하다가 구글링을 해봤더니 아파치재단의 버그 트래커에 이미 오류로 등록된 문제였습니다.

결론은 Commons FileUpload가 rfc1867을 지키지 않고 있다는 것입니다. 하지만 rfc1521은 세미콜론을 구분자로 제시하고 있고 대부분의 브라우져가 세미콜론을 구분자로 사용하기 때문에, 쉼표와 세미콜론을 모두 지원하는 방향으로 결정이 난 것 같습니다.

아래의 링크에서 관련 정보와 패치를 받으실 수 있습니다. 제가 패치한 jar 파일을 올리려다가 소스 등까지 다 같이 올려야하는게 귀찮아서 링크만 올립니다.

[fileupload] separator of boundary doesnt match rfc1867 examples

댓글()
  1. BlogIcon 모근원 2008.10.21 21:16 댓글주소  수정/삭제  댓글쓰기

    정말 감사합니다 ㅠ
    같은 오류로 고생하고있었는데... 역시나 1.2 버젼 버그더군요 ㅠ
    6시간동안 헛짓한것이 한순간에 씻기는 기분입니다 :-)