반응형

스프링 부트 1.5 릴리즈 노트

원문: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.5-Release-Notes

스프링 부트 1.4에서 업그레이드된 것

스프링부트 1.4이후 디프리케이트된것들

스프링부트 1.4에서 디프리케이트된 클래스, 메소드 그리고 프로퍼티들이 이번 릴리즈에서 제거되었다. 업그레이드전 디프리케이트된 메소드를 호출하는지 확인하자. 특히 HornetQ와 벨로시티 Velocity서포트가 삭제되었다.


이름이 바뀐 스타터들

스프링부트 1.4에서 이름이 바뀐 다음의 스타터들이 이번에 삭제되었다. 만일 "해결할수 없는 의존성 Unresolved dependency" 에러가 뜬다면 사용중인 스타터 이름이 올바른지 확인해보자:

  • spring-boot-starter-ws → spring-boot-starter-web-services

  • spring-boot-starter-redis → spring-boot-starter-data-redis

@ConfigurationProperties validation

JSR-303 규약 어노테이션을 사용하는 @ConfigurationProperties 클래스를 가지고 있다면 이제 그것들에 추가적으로 @Validated 어노테이션을 해줘야한다. 이미 있는 유효성은 여전히 잘 동작할것이지만 로그에 warning이 뜬것이다. 머지않아 @Validated 이 없는 클래스는 사용할 수 없을 것이다. 

스프링 세션 저장 Spring Session store

이제껏 스프링 세션과 레디스를 특별한 설정없이 사용해왔다면, 레디스는 자동으로 세션을 저장하는데 사용되었다. 이제는 저장 타입을 명시해주어야한다. 레디스와 스프링 세션을 사용하는 사용자들은 다음의 설정을 추가 해주어야한다:

spring.session.store-type=redis

액츄에이터 보안 Actuator security

Actuator "sensitive" endpoints are now secure by default (even if don’t have a dependency on "Spring Security"). If your existing Spring Boot 1.4 application makes use of Spring Security (and doesn’t have any custom security configuration) things should work as before. If your existing Spring Boot 1.4 application has custom security configuration and you wish to have open access to your sensitive endpoints, you will need to explicitly configure that in your security configuration. If you’re upgrading a Spring Boot 1.4 application that doesn’t have dependency on Spring Security and you wish to retain open access to your sensitive endpoints you’ll need to set management.security.enabled to false. See the updated reference documentation for more details.

The default role required to access the endpoints has also changed from ADMIN to ACTUATOR. This is to prevent accidental exposure of endpoints if you happen to use the ADMIN role for other purposes. If you want to restore Spring Boot 1.4 behavior set the management.security.roles property to ADMIN.

인메모리 매트릭스 리파지토리 InMemoryMetricRepository

InMemoryMetricRepository는 더이상 직접적으로 MultiMetricRepository를 구현하지않는다.  정식 InMemoryMetricRepository에 의해 뒷받침되어 MultiMetricRepository 인터페이스를 만족시키는 새로운 InMemoryMultiMetricRepository 빈이 이제 등록되었다. 대부분의 사용자가 MetricRepository 또는 MultiMetricRepository 인터페이스를 사용하고 있으므로 이 변화는 직접 보여지지않는다.  

spring.jpa.database

The spring.jpa.database 는 spring.datasource.url 프로퍼티를 통한 일반적인 데이터 베이스를 자동으로 찾아준다. 만일 spring.jpa.database를 수동으로 정의하며 사용해왔고 일반적인 데이터베이스를 사용하고 있다면 이 프로퍼티들을 다 없애버려도 될것이다.

하나 이상의 Dialect 를 가진 몇몇의 데이터베이스 (이를테면 Microsoft SQL Server 는 3개를 가지고있다) 그리고 당신이 사용중인 데이터베이스의 버젼이 설정한 것과 맞지 않는다면, 이전에 잘 작동한 설정을 가지고 하이버네이트의 Dialect자동 찾기에 맡기기 원한다면 spring.jpa.database=default 로 설정하자. 대안으로  spring.jpa.database-platform 프로퍼티를 사용하여 당신의 dialect를 설정할 수 있다.

@IntegrationComponentScan

스프링 Integration의 @IntegrationComponentScan 어노테이션은 이제 자동 설정된다. 권장되는 프로젝트 구조를 따른다면 당신은 이것을 지워줘야한다.

ApplicationStartedEvent

현재 당신의 코드에서 ApplicationStartedEvent를 위한 리스너 listener가 있다면,  ApplicationStartingEvent를 쓰도록 코드를 리팩토링 해주어야한다. 우리는 이 클래스가 무엇을 하는지 더 정확하게 알수 있게 이름을 바꾸었다.

Spring Integration Starter

spring-boot-starter-integration POM 은 더이상 spring-integration-jmx를 포함되지 않는다. 만일 당신이 Spring Integration JMX support가 필요하다면 spring-integration-jmx 의존성을 스스로 추가해줘어야한다.

Devtools excluded by default

메이븐과 그레들 플러그인 둘다 이제 기본적으로 "fat" jars에 spring-boot-devtools jar를 패키징 하지않는다. 당신이 devtools 원격 서포트를 사용중이라면, 이제 당신의 build.gradle 또는 pom.xml 파일에 excludeDevtools 프로퍼티를 명시적으로 설정해주어야한다.

Gradle 1.x

스프링 부트 그래들 플러그인은 이제 더이상 그래들 1.x와 그래들 2.x 초기버전과 호환되지 않는다. 그래들 2.9 이상 버전인지 확인하자.

Remote CRaSH shell

불행히도 remote SSH support을 제공하고저 스프링부트에서 사용하는 CRaSH project 는 더이상 유지가 되지않고 있으므로 우리는 remote actuator SSH support을 디프리케이트 하기로 결정하였고 스프링 부트 2.0에서 완전히 제거될 예정이다.

OAuth 2 Resource Filter

OAuth2 리소스 필터의 기본 순서가 3에서 SecurityProperties.ACCESS_OVERRIDE_ORDER - 1 로 변경되었다. 이 지점은 the actuator endpoints 바로 뒤이고 basic authentication filter chain 전이다. 이 기본값은 security.oauth2.resource.filter-order = 3 으로 설정하면 예전값으로 되돌릴 수 있다.

JSP servlet

JSP 서블릿응ㄴ 이제 더이상 기본값으로 개발모드가 아니다. 개발 모드는 DevTools을 쓸때 자동적으로 활성화 된다.  server.jsp-servlet.init-parameters.development=true.설정을 통해 명시적으로 활성화 할 수도 있다. 

Ignored paths and @EnableWebSecurity

스프링 부트 1.4 또는 이전 버전에서 Actuator는 항상 어떤 Ignored paths를 설정하여 @EnableWebSecurity의 사용을 무시해왔다. 이것은 1.5에서 바로 잡았으며  @EnableWebSecurity 를 사용하면 당신에게 완전한 제어가 가능했던 웹 보안의 자동 설정이 꺼질 것이다.

새로운 사항 및 주목할만한 점

Tip
Check the configuration changelog for a complete overview of the changes in configuration.

Third-party library upgrades

서드파티 라이브러리의 버전이 최신 버젼으로 업그레이드 되었다. 이 업데이트는 pring Data Ingalls, Jetty 9.4, JooQ 3.9, AssertJ 2.6.0, Hikari 2.5 그리고 Neo4J 2.1 이며 몇몇 메이븐 플러그인도 업그레이드 되었다.

Loggers endpoint

새로운 액츄에이터 loggers endpoint는 동작중인 어플리케이션의 로깅 레벨을 바꿀수 있게 해준다. 이는 JMX와 MVC endpoint에도 사용할수있다. 예를 들면 MVC endpoint의 로깅레벨을 바꾸려면 다음의 JSON를 /loggers/com.yourcorp.application에  post로 이슈해주면 된다:

{
  "configuredLevel": "DEBUG"
}

JMX endpoint를 사용하는 로거를 업데이트하려면  setLogLevel 를 사용하면 되는데 자세한 사항은 the updated documentation에서 확인하자.

Apache Kafka support

스프링 부트 1.5는 spring-kafka프로젝트를 통해 아파치 Kafka 자동설정을 지원한다. 손쉽게 Kafka를 사용하려면  spring-kafka 의존성과 `spring.kafka.* 어플리케이션 프로퍼티를 적절하게 설정해주면 된다.

Kafka로 부터 메세지를 받으려면 어노테이션 메소드를 쓰는게 제일 간단하다: 

@Component
public class MyBean {

    @KafkaListener(topics = "someTopic")
    public void processMessage(String content) {
        // ...
    }

}

Cloud Foundry actuator extensions

Spring Boot’s actuator module now includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The /cloudfoundryapplication path provides an alternative secured route to all NamedMvcEndpoint beans.

Cloud Foundry management UIs can make use of the endpoint to display additional actuator information. For example, Pivotal Cloud Foundry shows health information next to the application status:

apps manager

You can read more about the Cloud Foundry endpoint in the reference documentation and for and example of the kinds of things it can be used for you can read this blog post about PCF 1.9.

LDAP support

스프링 부트는 이제 어떤 표준 규약을 따르는 LDAP 서버를 자동설정해준다. 뿐만 아니라 Unbounded를 사용하여 내장 인메모리 LDAP 서버를 지원한다.

자세한 사항은 the documentation를 확인하자.

AuditEvents Endpoint Support

A new AuditEventsJmxEndpoint bean now allows you to query previously recorded AuditEvents over JMX. The MBean exposes AuditEventRepository find methods via getDataoperations. Audits are automatically recoded for authentication and authorization event and you can record your own events using the AuditEventRepository. That information is also exposed by a new /auditevents MVC endpoint.

Transaction manager properties

이제  spring.transaction.* 프로퍼티를 사용하여 PlatformTransactionManager를 자동설정해주는 다양한 aspects를 설정하는것이 가능해졌다. 현재는 "default-timeout" 과  rollback-on-commit-failure 프로퍼티가 지원된다.

JmxEndpoint interface

새로운 JmxEndpoint 인터페이스가 소개되어 당신이 액츄에이터 actuator endpoint를 JMX를 통해서만 노출되도록 개발할 수 있다. 이 인터페이스는 이미 MVC only endpoint를 제공해주는  MvcEndpoint 인터페이스와 매우 유사하다.

Vendor specific flyway migrations

You can now define flyway migration that are specific to a database vendor. To use vendor specific migrations, set the flyway.locations property as follows:

flyway.locations=db/migration/{vendor}

See this how-to for more details.

Deprecation level

It is now possible to define a deprecation level for a property in the metadata. The level can either be warning (default) or error.

Here is an example of manual metadata for a property that got moved in Spring Boot 2:

{
  "name": "server.context-parameters",
  "type": "java.util.Map<java.lang.String,java.lang.String>",
  "description": "ServletContext parameters.",
  "deprecation": {
    "level": "error",
    "replacement": "server.servlet.context-parameters"
  }
}

So far, when a deprecated property is not bound anymore, we remove the metadata altogether. This new feature allows to flag a property (server.context-parameters here) as an error. Newer versions of your favorite IDE should use that to offer assistance.

테스팅 업데이트 Testing updates

이제 @Test…​a로 시작하는 어노테이션에 의해 임포트import되던 자동설정을 제외할 수 있게 되었다. 모든 현존하는  @Test…​어노테이션들은 이제 excludeAutoConfiguration 속성값을 가지게 되었다. 또 다른 방법으로 당신의 테스트코드에 직접적으로  @ImportAutoConfiguration(exclude=…​)를 추가해줘도 된다.

스프링 부트 1.5에서 새로운 @JdbcTest 어노테이션이 소개되어 직접 JDBC과 상호연동되는 테스트를 할 수 있다.

Custom fat jar layouts

스프링 부트 메이븐과 그래들 플러그인은 이제 far jar 레이아웃을 커스터마이즈할 수 있게 지원한다. 이 기능은 스프링부트의 영역 밖에서 개발된  다음과 같은 실험적인 레이아웃을 가능하게 해준다. 더 자세한 업데이트된 문서를 참고하자

JmsTemplate customizations

이제  spring.jms.template.* 네임스페이스의 추가된 키값을 사용하여 자동설정된  JmsTemplate을 커스터마이즈 할수 있게 되었다.

Miscellaneous

  • Mockito 2.x 은 이제  @MockBean 으로 사용할 수 있다.(Mockito 1.9 와 호환가능함)

  • 내장 런쳐 스크린트는 이제 a force-stop을 지원한다. 

  • 카산드라를 위한 새로운 health check가 추가되었다.

  • 카산드라 사용자 정의 타입들이 이제 해결되었다. (스프링 데이터의 SimpleUserTypeResolver를 통해)

  • The skip 프로퍼티는 이제  스프링 부트 메이븐 플러그인  run 에서, 'stop' 그리고 'repackage` goals 에서 사용할 수 있다.

  • 복수개의 main m메소드 클래스가 있다면, 메이븐과 그래들 플러그인은 이제 자동적으로  @SpringBootApplication 어노테이션이 있는것을 실행할 것이다.

Deprecations in Spring Boot 1.5

  • TomcatEmbeddedServletContainerFactory.setTldSkip has been deprecated in favor of setTldSkipPatterns

  • ApplicationStartedEvent has been replaced by ApplicationStartingEvent

  • Several constants in LoggingApplicationListener have been replaced by versions in LogFile

  • Caching with Guava has been deprecated since Guava support will be dropped in Spring Framework 5. Upgrade to Caffeine

  • CRaSH support has been deprecated since it’s no longer actively maintained

  • Several protected methods in EndpointMBeanExporter have been deprecated following the introduction of JmxEndpoint

  • SearchStrategy.PARENTS has been replaced with SearchStrategy.ANCESTORS.

  • Apache DBCP support has been deprecated in favor of DBCP 2

  • The server.undertow.buffers-per-region property has been deprecated because it is not used (see UNDERTOW-587)

  • @AutoConfigureTestDatabase has been moved from org.springframework.boot.test.autoconfigure.orm.jpa to org.springframework.boot.test.autoconfigure.jdbc

프로퍼티 이름변경 Property Renames

  • server.max-http-post-size 프로퍼티는 특정기술 형태값으로 바뀌었다. (예를 들면, server.tomcat.max-http-post-size)

  • spring.data.neo4j.session.scope 프로퍼티는 제거되었다.


반응형

반응형

스프링 부트 1.4 릴리즈 노트 - 2017년 1월 19일

원문: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes

스프링부트 1.3이후 업그레이드된 것

스프링 부트 1.3에서 더이상 지원하지않는 것 Deprecations from Spring Boot 1.3

스프링 부트 1.3에서 디프리케이트된 클래스, 메소드, 프로퍼티들은 이번 릴리즈에서 제거되었다.업그레이드에 앞서 디프리케이트된 메소드를 호출하는지 먼저 확인해야한다.

Log4j 1 지원은 Apache EOL announcement 의거하여 제거되었다.

재명명된 스타터들 Renamed starters

다음의 스타터들의 이름이 변경되었다.기존의 이름은 스프링 부터 2.0에서 제거될 것이다.

  • spring-boot-starter-ws → spring-boot-starter-web-services

  • spring-boot-starter-redis → spring-boot-starter-data-redis

DataSourceProperties의 get 메소드들 DataSourceProperties get methods

DataSourceProperties의 몇몇 get…​ 메소드들은 다른 @ConfigurationProperties 클래스들과 더 일관성있게 바뀌었다. 만약 이전에 다음의 메드들을 코드에 직접적으로 호출했었다면 동일한 기능의 새 determine…​로 바꿔줘야한다.

  • getDriverClassName() → determineDriverClassName()

  • getUrl() → determineUrl()

  • getUsername() → determineUsername()

  • getPassword() → determineUsername()

Note
The get

 메소드는 디프리케이트 되이 않았다. 하지만 이들의 행동이 바뀌었기때문에 당신은 업그레이드할때 수동으로 확인해줘야한다.

DataSource 바인딩 DataSource binding

스프링 부트 1.4 이전에는 자동 설정된 datasource들은 spring.datasourcenamespace. In 1.4, we only bind the common settings to spring.datasource (seeDataSourceProperties) and we have defined new specific namespaces for the four connections pools we support (in that order):
alents:ethods from DataSourceProperties 프링 부트 1.2에선 logging.config 를 써서 로깅 설정파일을 커스터마이즈할 수 있었다. 파일이 존스프링 부트 1.4 이전에는 자동설정된 datasource들은 spring.datasource 네임스페이스에 바인드되었다. 1.4부터 우리는 일반적인 설정만 spring.datasource에 바인드된다(DataSourceProperties를 보자) 그리고 우리가 지원하는 4개의 커넥션풀을 위한 새로운 특정 네임스페이스 정의하였다 (순서대로):
  • org.apache.tomcat.jdbc.pool.DataSource를 위한 spring.datasource.tomcat 

  • com.zaxxer.hikari.HikariDataSource를 위한 spring.datasource.hikari

  • org.apache.commons.dbcp.BasicDataSource를 위한 spring.datasource.dbcp 

  • org.apache.commons.dbcp2.BasicDataSource를 위한 spring.datasource.dbcp2

만일 당신이 사용하는 커넥션풀의 구현물의 특정설정을 사용하고 있다면, 연관된 네임스페이스로 설정을 옮겨줘야한다. 예를 들어, 톰캣의 testOnBorrow 플래그를 사용하고 있다면, spring.datasource.test-on-borrow 에서 spring.datasource.tomcat.test-on-borrow로 옮겨줘야한다.

만일 당신이 사용하는 IDE에서 설정을 도움받았다면, spring.datasource 네임스페이스에 이들을 모두 함께 사용하지않고 커넥션 풀당 어느 설정이 사용가는한지 볼 수 있다. 이는 어느 구현체가 어느 기능을 지원하는지 알아둬야 하는 당신의 삶을 더 쉽게 만들어줄 것이다.

JTA설정 바인딩 JTA settings binding

DataSource binding과 유사하게 Atomikos와 Bitronix 를 위한 특정 JTA제공자 설정 프로퍼티가 spring.jta에 바인드 된다. 이들은 이제 spring.jta.atomikos.properties와 spring.jta.bitronix.properties에 각각 바인드 될 것이다; 이들 엔트리를 위한 메타데이터 또한 크게 향상되었다.

하이버네이트 5 Hibernate 5

하이버네이트 5는 이제 기본 JPA 퍼시스턴스 제공자로서 사용된다. 만일 스프링 부트 1.3에서 업그레이드한다면, 하이버네이트 4.3에서 5.0으로 바꿔줘야한다. 일반적인 업그레이드 방침은 Hibernate migration documentation를 참고하자. 추가적으로 당신은 다음의 것들을 알아둬야한다:

네이밍 전략 Naming Strategy

하이버네이트 5.1이 이전의 NamingStrategy 인터페이스를 지원을 삭제함으로서 SpringNamingStrategy 는 더이상 사용되지 않는다. 새로운 SpringPhysicalNamingStrategy 가 이제 자동설정되어 하이버네이트의 기본 ImplicitNamingStrategy와 함께 사용된다. 이는 스프링부트 1.3의 기본설정과 매우 유사하다 (동일하진않다). 하지만 당신은 업그레이드시 데이터베이스 스키마가 올바른지 확인해주어야 할것이다.

만일 당신이 업그레이드 전 이미 하이버네이트 5를 사용중이라면, 아마 하이버네이트5의 기본설정을 사용하고 있을 것이다. 업그레이드 후에 이를 되돌리길 원하면 당신의 설정에 이 프로퍼티를 설정하면 된다:

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

제네레이터 매핑 Generator mappings

업그레이드의 고통을 최소화하기 위해, 우리는 하이버네이트5의 hibernate.id.new_generator_mappings을 false를로 설정해두었다. 하이버네이트 팀은 보통 이 설정을 권장하지않는다. 따라서 당신이 제네레이터 변경을 따르려면 당신의 application.properties 파일에 hibernate.id.new_generator_mappings을 true로 설정하면 된다.

하이버네이트 4.3으로 다운그레이드 Downgrading to Hibernate 4.3

하이버네이트 5.0으로 업그레이드하는데 문제가 있다면, pom.xml파일의 hibernate.version 프로퍼티를 오버라이딩함으로서 예전 버젼의 하이버네이트로 다운그레이드 할 수 있다. 

<properties>
    <hibernate.version>4.3.11.Final</hibernate.version>
</properties>

또는 그레들을 사용한다면 hibernate.version 프로퍼티를 다음과 같이 오버라이딩하면 된다:

ext['hibernate.version'] = '4.3.11.Final'
Note

하이버네이트 4.3 은 스프링부터 1.4에서 지원하지 않는다 업그레이드를 방해하는 버그가 있다면  이슈를 제기하자.


@EntityScan

@org.springframework.boot.orm.jpa.EntityScan 어노테이션은 디프리케이트 되어 @org.springframework.boot.autoconfigure.domain.EntityScan 로 변경해주거나 외부 설정을 해주어야한다.

예를 들어 만일 다음의 설정을 가지고 있다면:

import org.springframework.boot.autoconfigure.SpringApplication;
import org.springframework.boot.orm.jpa.EntityScan;

@SpringBootApplication
@EntityScan(basePackageClasses=Customer.class)
public class MyApplication {

    // ....

}

만일 자동설정된 LocalContainerEntityManagerFactoryBean을 사용중이라면 다음과 같이 바꿔준다:

import org.springframework.boot.autoconfigure.SpringApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;

@SpringBootApplication
@EntityScan(basePackageClasses=Customer.class)
public class MyApplication {

    // ....

}

또는 스스로 LocalContainerEntityManagerFactoryBean 을 설정중이라면, @EntityScan 어노테이션을 통째로 버리고 LocalContainerEntityManagerFactoryBean.setPackagesToScan(…​) 를 호출하거나 또는 EntityManagerFactoryBuilder packages(…​) 메소드를 사용해야한다:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(...)
        .properties(...)
        .packages(Customer.class)
        .build();
}

테스트 유틸리티와 클래스들 Test utilities and classes

스프링 부트 1.4는 org.springframework.boot.test 패키지를 완전히 재구성된 새로운 spring-boot-test 모듈을 추가하였다. 스프링 부트 1.3 어플리케이션에서 업그레이드할 때, 예전 패키지들의 디프리케이트된 클래스들을 새 구조의 동일한 클래스로 바꿔주어야한다. 리눅스 또는 OSX를 쓰고있다면 다음의 커맨드를 사용해서 코드를 마이그레잇할 수 있다:

find . -type f -name '*.java' -exec sed -i '' \
-e s/org.springframework.boot.test.ConfigFileApplicationContextInitializer/org.springframework.boot.test.context.ConfigFileApplicationContextInitializer/g \
-e s/org.springframework.boot.test.EnvironmentTestUtils/org.springframework.boot.test.util.EnvironmentTestUtils/g \
-e s/org.springframework.boot.test.OutputCapture/org.springframework.boot.test.rule.OutputCapture/g \
-e s/org.springframework.boot.test.SpringApplicationContextLoader/org.springframework.boot.test.context.SpringApplicationContextLoader/g \
-e s/org.springframework.boot.test.SpringBootMockServletContext/org.springframework.boot.test.mock.web.SpringBootMockServletContext/g \
-e s/org.springframework.boot.test.TestRestTemplate/org.springframework.boot.test.web.client.TestRestTemplate/g \
{} \;

추가적으로, 스프링 부트 1.4는 스프링부트 테스트를 돌릴 수 있는 다양한 방법들을 더 합리적이고 간단하게 하려는 시도를 했다. 당신의 다음의 기존 코드를 새로운 @SpringBootTest 어노테이션을 사용하도록 바꿀수 있다:

  • 기존 @SpringApplicationConfiguration(classes=MyConfig.class) 를 대체하는 새로운 @SpringBootTest(classes=MyConfig.class)

  • 기존 @ContextConfiguration(classes=MyConfig.class, loader=SpringApplicationContextLoader.class)를 대체하는 새로운 @SpringBootTest(classes=MyConfig.class)

  • 기존 @ContextConfiguration(classes=MyConfig.class, loader=SpringApplicationContextLoader.class) 를 대체하는 새로운 @SpringBootTest(classes=MyConfig.class)

  • 기존 @IntegrationTest 를 대체하는 새로운 @SpringBootTest(webEnvironment=WebEnvironment.NONE)

  • 기존 @IntegrationTest와 @WebAppConfiguration 를 대체하는 새로운 @SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT) (또는 RANDOM_PORT)

  • 기존 @WebIntegrationTest to@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT) (or RANDOM_PORT)

마이그레션 테스트 진행간에 당신은 또한 기존 @RunWith(SpringJUnit4ClassRunner.class)

선언문들을  스프링 4.3의 더 가독성이 좋은 @RunWith(SpringRunner.class).로 대체할 수 있다.

@SpringBootTest 어노테이션에 대한 더 자세한 정보는 다음의 링크를 참고하세요 updated documentation.

TestRestTemplate

TestRestTemplate 클래스는 더이상 직접적으로 RestTemplate 에서 extends되지 않는다. (비록 여전히 같은 메소드를 제공하긴하지만). 이로서 TestRestTemplate 는 의도치않게 주입(accidentally injected)되는 일 없이 하나의 빈 Bean으로서 설정하는게 가능해졌다.  RestTemplate 안에 실제 접근해야할 필요가 있다면 getRestTemplate() 메소드를 사용하자.


메이븐 Spring-boot.version 프로퍼티 Maven spring-boot.version property

The spring-boot.version property has been removed from the spring-boot-dependenciespom. See issue 5104 for details.

Integration Starter

spring-boot-starter-integration 은 일반적인 Spring Integration 어플리케이션에서 필요하지않은 4가지 모듈을 제거함으로서 간소화하였다.  제거된 4개의 모듈은 다음과 같다:

  • spring-integration-file

  • spring-integration-http

  • spring-integration-ip

  • spring-integration-stream

당신의 어플리케이션이 저 4개의 모듈중 하나라도 사용한다면 pom이나 build.gradle에 명시적 의존성을 추가해줘야할 것이다.

추가적으로,  spring-integration-java-dsl 과 spring-integration-jmx 은 이제 스타터에 추가되었다. DSL을 사용하는것은 당신의 어플리케이션의 Spring Intergation을 설정할때 권장되는 되는 방식이다.


Spring Batch Starter

spring-boot-starter-batch starter 는 더이상 embedded 데이터베이스에 의존성을 갖지않는다. 당신이 기존의 방식대로 사용하고 싶다면 당신이 원하는 데이터베이스 (드라이버)를 추가해줘야한다. 예를 들면:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

이미 다른 드라이버를 설정하여 hsqldb 를 exclusion해두었다면 이젠 exclusion을 지워버려도 된다.

Downgrading Tomcat

톰켓 8.5.4의 tomcat-juli 모듈이 이제 tomcat-embedded의 일부로 패키지 되었다.  수동으로 예전 버전의 톰켓으로 다운그레이드했었다면 이제 tomcat-juli 모듈을 추가해주어야할것이다. 자세한 방법은 다음의 문서를 참고하자 how-to documentation section.

Dispatch Options Request

spring.mvc.dispatch-options-request 의 기본 프로퍼티가  false 에서 스프링 프레임워크의 선호되는 값인 true 로 바뀌었다. 

 FrameworkServlet.doService의  OPTIONS 리퀘스트를 사용하지 않으려면 명시적으로 spring.mvc.dispatch-options-request 를 false.로 바꿔주어야한다.

Forced character encoding

캐릭터 인코딩 강제하기(forced) 이제 요청request에만 적용된다. (응답response는 아님). 요청request과 응답response 둘다 강제하려면 spring.http.encoding.force 를 true로 설정해주어야한다.

Multipart support

multipart 프로퍼티는 multipart에서 spring.http.multipart 로 바뀌었다.

Server header

 Server HTTP 응답헤더 response header 는 이제 server.server-header 프로퍼티를 설정해야지만 설정이 가능하다.

@ConfigurationProperties default bean names

When a @ConfigurationProperties bean is registered via@EnableConfigurationProperties(SomeBean.class), we used to generate a bean name of the form <prefix>.CONFIGURATION_PROPERTIES. As of Spring Boot 1.4, we have changed that pattern to avoid name clashes if two beans use the same prefix.

The new conventional name is <prefix>-<fqn>, where <prefix> is the environment key prefix specified in the @ConfigurationProperties annotation and <fqn> the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used.

Jetty JNDI support

spring-boot-starter-jetty "스타터Starter"는 더이상 org.eclipse.jetty:jetty-jndi를 포함하지않는다. JNDI를 제티와 같이 사용중이라면 이제 스스로 이 의존성을 직접 추가해줘야만 한다.

Guava caches

구아바 캐시Guava cache 지원을 사용중인 개발자는 Caffeine으로 이주할것을 권장한다.

Remote Shell

The CRaSH properties have moved from the shell. namespace to the management.shell.namespace. Also, the authentication type should now be defined viamanagement.shell.auth.type.

Spring Session auto-configuration improvements

Spring Boot supports more backend stores for Spring Session: alongside Redis, JDBC, MongoDB, Hazelcast and in memory concurrent hash maps are also supported. A newspring.session.store-type mandatory property has been introduced to select the store Spring Session should be using.

Launch script identity

When the launch script is determining the application’s default identity, the canonical name of the directory containing the jar will now be used. Previously, if the directory containing the jar was a symlink, the name of the symlink was used. If you require more control over the application’s identity, the APP_NAME environment variable should be used.

MongoDB 3

The default version of Mongo’s Java Driver is now 3.2.2 (from 2.14.2) and spring-boot-starter-data-mongodb has been updated to use the new, preferred mongodb-driver artifact.

The auto-configuration for Embedded MongoDB has also been updated to use 3.2.2 as its default version.

Thymeleaf 3

기본값으로 스프링 부트는 타임리프 2.1을 사용하지만 이제 타임리프3와도 호환된다. 자세한 내용은 업데이트된 문서 를 찾아보자.

Executable jar layout

실행가능한 jars (executable jars)의 레이아웃이 변경되었다. 스프링부트의 메이븐, 그래들 또는 앤트지원을 통해 빌드한다면 이 변화는 영향을 미치지 않을 것이다. 당신 스스로의 실행가능한 아카이브를 통해서 빌드한다면 이제 어플리케이션이 lib이 아니라 BOOT-INF/lib 에 패키지 된다는 것을 명심하라. 어플리케이션의 클래스들은 이제 jar의 루트가 아닌  BOOT-INF/classes 에 패키지 될것이다.

Integration tests with the maven-failsafe-plugin

As of Failsafe 2.19target/classes is no longer on the classpath and the project’s built jar is used instead. The plugin won’t be able to find your classes due to the change in the executable jar layout. There are two ways to work around this issue:

  1. Downgrade to 2.18.1 so that you use target/classes instead

  2. Configure the spring-boot-maven-plugin to use a classifier for the repackage goal. That way, the original jar will be available and used by the plugin. For example

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <classifier>exec</classifier>
    </configuration>
</plugin>
Note
If you are using Spring Boot’s dependency management, there is nothing to do as you’ll use 2.18.1 by default.
Tip
Watch SUREFIRE-1198 for updates on this issue.

HornetQ

HornetQ 지원은 디프리케이트 되었다. HornetQ 사용자들은 Artemis로 이주할것을 권장한다.

New and Noteworthy

Tip
Check the configuration changelog for a complete overview of the changes in configuration.

Spring Framework 4.3

Spring Boot 1.4 builds on and requires Spring Framework 4.3. There are a number of nice refinements in Spring Framework 4.3 including new Spring MVC @RequestMappingannotations. Refer to the Spring Framework reference documentation for details.

Note that the test framework in Spring Framework 4.3 requires JUnit 4.12. See SPR-13275for further details.

Third-party library upgrades

A number of third party libraries have been upgraded to their latest version. Updates include Jetty 9.3, Tomcat 8.5, Jersey 2.23, Hibernate 5.0, Jackson 2.7, Solr 5.5, Spring Data Hopper, Spring Session 1.2, Hazelcast 3.6, Artemis 1.3, Ehcache 3.1, Elasticsearch 2.3, Spring REST Docs 1.1, Spring AMQP 1.6 & Spring Integration 4.3.

Several Maven plugins were also upgraded.

Couchbase support

Full auto-configuration support is now provided for Couchbase. You can easily access aBucket and Cluster bean by adding the spring-boot-starter-data-couchbase "Starter" and providing a little configuration:

spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123
spring.couchbase.bucket.name=my-bucket
spring.couchbase.bucket.password=secret

It’s also possible to use Couchbase as a backing store for a Spring Data Repository or as aCacheManager. Refer to the updated documentation for details.

Neo4J Support

Auto-configuration support is now provided for Neo4J. You can connect to a remote server or run an embedded Neo4J server. You can also use Neo4J to back a Spring DataRepository, for example:

public interface CityRepository extends GraphRepository<City> {

    Page<City> findAll(Pageable pageable);

    City findByNameAndCountry(String name, String country);

}

Full details are provided in the Neo4J section of the reference documentation.

Redis Spring Data repositories

Redis can now be used to back Spring Data repositories. See the Spring Data Redisdocumentation for more details.

Narayana transaction manager support

Auto-configuration support is now included for the Narayana transaction manager. You can choose between Narayana, Bitronix or Atomkos if you need JTA support. See the updated reference guide for details.

Caffeine cache support

Auto-configuration is provided for Caffeine v2.2 (a Java 8 rewrite of Guava’s caching support). Existing Guava cache users should consider migrating to Caffeine as Guava cache support will be dropped in a future release.

Elasticsearch Jest support

Spring Boot auto-configures a JestClient and a dedicated HealthIndicator if Jest is on the classpath. This allows you to use Elasticsearch even when spring-data-elasticsearch isn’t on the classpath.

Analysis of startup failures

Spring Boot will now perform analysis of common startup failures and provide useful diagnostic information rather than simply logging an exception and its stack trace. For example, a startup failure due to the embedded servlet container’s port being in use looked like this in earlier versions of Spring Boot:

2016-02-16 17:46:14.334 ERROR 24753 --- [           main] o.s.boot.SpringApplication               : Application startup failed

java.lang.RuntimeException: java.net.BindException: Address already in use
    at io.undertow.Undertow.start(Undertow.java:181) ~[undertow-core-1.3.14.Final.jar:1.3.14.Final]
    at org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainer.start(UndertowEmbeddedServletContainer.java:121) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:293) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at sample.undertow.SampleUndertowApplication.main(SampleUndertowApplication.java:26) [classes/:na]
Caused by: java.net.BindException: Address already in use
    at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_60]
    at sun.nio.ch.Net.bind(Net.java:433) ~[na:1.8.0_60]
    at sun.nio.ch.Net.bind(Net.java:425) ~[na:1.8.0_60]
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) ~[na:1.8.0_60]
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74) ~[na:1.8.0_60]
    at org.xnio.nio.NioXnioWorker.createTcpConnectionServer(NioXnioWorker.java:190) ~[xnio-nio-3.3.4.Final.jar:3.3.4.Final]
    at org.xnio.XnioWorker.createStreamConnectionServer(XnioWorker.java:243) ~[xnio-api-3.3.4.Final.jar:3.3.4.Final]
    at io.undertow.Undertow.start(Undertow.java:137) ~[undertow-core-1.3.14.Final.jar:1.3.14.Final]
    ... 11 common frames omitted

In 1.4, it will look like this:

2016-02-16 17:44:49.179 ERROR 24745 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

If you still want to see the stacktrace of the underlying cause, enable debug logging fororg.springframework.boot.diagnostics.LoggingFailureAnalysisReporter.

Image Banners

You can now use image files to render ASCII art banners. Drop a banner.gifbanner.jpg orbanner.png file into src/main/resources to have it automatically converted to ASCII. You can use the banner.image.width and banner.image.height properties to tweak the size, or usebanner.image.invert to invert the colors.

banner image

RestTemplate builder

A new RestTemplateBuilder can be used to easily create a RestTemplate with sensible defaults. By default, the built RestTemplate will attempt to use the most suitableClientHttpRequestFactory available on the classpath and will be aware of theMessageConverter instances to use (including Jackson). The builder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC auth support you can use:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.basicAuthorization("user", "secret").build();
}

The auto-configured TestRestTemplate now uses the RestTemplateBuilder as well.

JSON Components

A new @JsonComponent annotation is now provided for custom Jackson JsonSerializer and/orJsonDeserializer registration. This can be a useful way to decouple JSON serialization logic:

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer<SomeObject> {
        // ...
    }

    public static class Deserializer extends JsonDeserializer<SomeObject> {
        // ...
    }

}

Additionally, Spring Boot also now provides JsonObjectSerializer and JsonObjectDeserializerbase classes which provide useful alternatives to the standard Jackson versions when serializing objects. See the updated documentation for details.

Convention based error pages

Custom error pages for a given status code can now be created by following a convention based approach. Create a static HTML file in /public/error or add a template to/templates/error using the status code as the filename. For example, to register a custom 404 file you could add src/main/resource/public/error/404.html. See the updated reference documentation for details.

Unified @EntityScan annotation

org.springframework.boot.autoconfigure.domain.EntityScan can now be used to specify the packages to use for JPA, Neo4J, MongoDB, Cassandra and Couchbase. As a result, the JPA-specific org.springframework.boot.orm.jpa.EntityScan is now deprecated.

ErrorPageRegistry

New ErrorPageRegistry and ErrorPageRegistrar interfaces allow error pages to be registered in a consistent way regardless of the use of an embedded servlet container. TheErrorPageFilter class has been updated to that it is now a ErrorPageRegistry and not a fakeConfigurableEmbeddedServletContainer.

PrincipalExtractor

The PrincipalExtractor interface can now be used if you need to extract the OAuth2Principal using custom logic.

Test improvements

Spring Boot 1.4 includes a major overhaul of testing support. Test classes and utilities are now provided in dedicated spring-boot-test and spring-boot-test-autoconfigure jars (although most users will continue to pick them up via the spring-boot-starter-test"Starter"). We’ve added AssertJ, JSONassert and JsonPath dependencies to the test starter.

@SpringBootTest

With Spring Boot 1.3 there were multiple ways of writing a Spring Boot test. You could use@SpringApplicationConfiguration@ContextConfiguration with theSpringApplicationContextLoader@IntegrationTest or @WebIntegrationTest. With Spring Boot 1.4, a single @SpringBootTest annotation replaces all of those.

Use @SpringBootTest in combination with @RunWith(SpringRunner.class) and set thewebEnvironment attribute depending on the type of test you want to write.

A classic integration test, with a mocked servlet environment:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    // ...

}

A web integration test, running a live server listening on a defined port:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvionment.DEFINED_PORT)
public class MyTest {

    // ...

}

A web integration test, running a live server listening on a random port:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvionment.RANDOM_PORT)
public class MyTest {

	@LocalServerPort
	private int actualPort;

	// ...

}

See the updated reference documentation for details.

Auto-detection of test configuration

Test configuration can now be automatically detected for most tests. If you follow the Spring Boot recommended conventions for structuring your code the @SpringBootApplication class will be loaded when no explicit configuration is defined. If you need to load a different@Configuration class you can either include it as a nested inner-class in your test, or use theclasses attribute of @SpringBootTest.

See Detecting test configuration for details.

Mocking and spying beans

It’s quite common to want to replace a single bean in your ApplicationContext with a mock for testing purposes. With Spring Boot 1.4 this now as easy as annotating a field in your test with @MockBean:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @MockBean
    private RemoteService remoteService;

    @Autowired
    private Reverser reverser;

    @Test
    public void exampleTest() {
        // RemoteService has been injected into the reverser bean
        given(this.remoteService.someCall()).willReturn("mock");
        String reverse = reverser.reverseSomeCall();
        assertThat(reverse).isEqualTo("kcom");
    }

}

You can also use @SpyBean if you want to spy on an existing bean rather than using a full mock.

See the mocking section of the reference documentation for more details.

Auto-configured tests

Full application auto-configuration is sometime overkill for tests, you often only want to auto-configure a specific "slice" of your application. Spring Boot 1.4 introduces a number of specialized test annotations that can be used for testing specific parts of your application:

  • @JsonTest - For testing JSON marshalling and unmarshalling.

  • @WebMvcTest - For testing Spring MVC @Controllers using MockMVC.

  • @RestClientTest - For testing RestTemplate calls.

  • @DataJpaTest - For testing Spring Data JPA elements

Many of the annotations provide additional auto-configuration that’s specific to testing. For example, if you use @WebMvcTest you can @Autowire a fully configured MockMvc instance.

See the reference documentation for details.

JSON AssertJ assertions

New JacksonTesterGsonTester and BasicJsonTester classes can be used in combination with AssertJ to test JSON marshalling and unmarshalling. Testers can be used with the@JsonTest annotation or directly on a test class:

@RunWith(SpringRunner.class)
@JsonTest
public class MyJsonTests {

    private JacksonTester<VehicleDetails> json;

    @Test
    public void testSerialize() throws Exception {
        VehicleDetails details = new VehicleDetails("Honda", "Civic");
        assertThat(this.json.write(details)).isEqualToJson("expected.json");
        assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
    }

}

See the JSON section of the reference documentation or the Javadocs for details.

@RestClientTest

The @RestClientTest annotation can be used if you want to test REST clients. By default it will auto-configure Jackson and GSON support, configure a RestTemplateBuilder and add support for MockRestServiceServer.

Auto-configuration for Spring REST Docs

Combined with the support for auto-configuring MockMvc described above, auto-configuration for Spring REST Docs has been introduced. REST Docs can be enabled using the new @AutoConfigureRestDocs annotation. This will result in the MockMvc instance being automatically configured to use REST Docs and also removes the need to use REST Docs' JUnit rule. Please see the relevant section of the reference documentation for further details.

Test utilities

spring-boot-starter-test now brings the AssertJ assertions library.

Test utilities from the org.springframework.boot.test package have been moved to a spring-boot-test dedicated artifact.

Actuator info endpoint improvements

You can now use the InfoContributor interface to register beans that expose information to the /info actuator endpoint. Out of the box support is provided for:

  • Full or partial Git information generated from the git-commit-id-plugin Maven or gradle-git-properties Gradle plugin (set management.info.git.mode=full to expose full details)

  • Build information generated from the Spring Boot Maven or Gradle plugin.

  • Custom information from the Environment (any property starting info.*)

Details are documented in the "Application information" section of the reference docs.

MetricsFilter improvements

The MetricsFilter can now submit metrics in both the classic "merged" form, or grouped per HTTP method. Use endpoints.metrics.filter properties to change the configuration:

endpoints.metrics.filter.gauge-submissions=grouped
endpoints.metrics.filter.counter-submissions=grouped,merged

Spring Session JDBC Initializer

If Spring Session is configured to use the JDBC store, the schema is now created automatically on startup.

Secured connection for Artemis/HornetQ

Spring Boot now allows to connect against a secured Artemis/HornetQ broker.

Miscellaneous

  • server.jetty.acceptors and server.jetty.selectors properties have been added to configure the number of Jetty acceptors and selectors.

  • server.max-http-header-size and server.max-http-post-size can be used to constrain maximum sizes for HTTP headers and HTTP POSTs. Settings work on Tomcat, Jetty and Undertow.

  • The minimum number of spare threads for Tomcat can now be configured usingserver.tomcat.min-spare-threads

  • Profile negation in now supported in application.yml files. Use the familiar ! prefix inspring.profiles values

  • The actuator exposes a new headdump endpoint that returns a GZip compressed hprofheap dump file

  • Spring Mobile is now auto-configured for all supported template engines

  • The Spring Boot maven plugin allows to bundle system scoped artifacts using the newincludeSystemScope attribute

  • spring.mvc.log-resolved-exception enables the automatic logging of a warning when an exception is resolved by a HandlerExceptionResolver

  • spring.data.cassandra.schema-action you be used to customize the schema action to take on startup

  • Spring Boot’s fat jar format should now consume much less memory

  • Locale to Charset mapping is now supported via the spring.http.encoding.mapping.<locale>=<charset> property

Spring Data "Ingalls" release train support

Spring Boot 1.4 GA ships with the Spring Data "Hopper" release out of the box. Users that would like to try the "Ingalls" release train (available in milestone one at the time of writing) can do so by just setting the spring-data-releasetrain.version property to Ingalls-M1 and declaring the Spring milestone repository.

Depending on what modules of Spring Data you use, you might have to upgrade a couple of transitive dependencies, too:

  • Spring Data REST users will have to upgrade to Spring HATEOAS 0.21 (set spring-hateoas.version to 0.21.0.RELEASE)

  • Spring Data Redis users using Jedis as driver will have to upgrade to 2.9 (setjedis.version to 2.9.0)

Deprecations in Spring Boot 1.4

  • Velocity support has been deprecated since support has been deprecated as of Spring Framework 4.3.

  • Some constructors in UndertowEmbeddedServletContainer have been deprecated (most uses should be unaffected).

  • The locations and merge attributes of the @ConfigurationProperties annotation have been deprecated in favor of directly configuring the Environment.

  • The protected SpringApplication.printBanner method should no longer be used to print a custom banner. Use the Banner interface instead.

  • The protected InfoEndpoint.getAdditionalInfo method has been deprecated in favor of the InfoContributor interface.

  • org.springframework.boot.autoconfigure.test.ImportAutoConfiguration has been moved toorg.springframework.boot.autoconfigure.

  • All classes in the org.springframework.boot.test package have been deprecated. See the "upgrading" notes above for details.

  • PropertiesConfigurationFactory.setProperties(Properties) is deprecated in favor of usingPropertySources.

  • Several classes in the org.springframework.boot.context.embedded package have been deprecated and relocated to org.springframework.boot.web.servlet.

  • All classes in the org.springframework.boot.context.web package have been deprecated and relocated.

  • The spring-boot-starter-ws "Starter" has been renamed to spring-boot-starter-web-services.

  • The spring-boot-starter-redis "Starter" has been renamed to spring-boot-starter-data-redis.

  • The spring-boot-starter-hornetq starter and auto-configuration has been deprecated in favour of using spring-boot-starter-artemis

  • management.security.role has been deprecated in favour of management.security.roles

  • The @org.springframework.boot.orm.jpa.EntityScan annotation has been deprecated in favor of @org.springframework.boot.autoconfigure.domain.EntityScan or explicit configuration.

  • TomcatEmbeddedServletContainerFactory.getValves() has been deprecated in favor ofgetContextValves().

  • org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter has been deprecated in favor of org.springframework.boot.system.EmbeddedServerPortFileWriter

  • org.springframework.boot.actuate.system.ApplicationPidFileWriter has been deprecated in favor of org.springframework.boot.system.ApplicationPidFileWriter

Property Renames

  • spring.jackson.serialization-inclusion should be replaced with spring.jackson.default-property-inclusion.

  • spring.activemq.pooled should be replaced with spring.activemq.pool.enabled.

  • spring.jpa.hibernate.naming-strategy should be replaced withspring.jpa.hibernate.naming.strategy.

  • server.tomcat.max-http-header-size should be replaced with server.max-http-header-size.



반응형

반응형

자바에서 요일(day of week)을 구하는 간단한 방법

(원문:http://www.leveluplunch.com/java/examples/get-day-of-week/)


Java Calendar

Calendar cal = Calendar.getInstance();

cal.set(Calendar.MONTH, Calendar.APRIL);

cal.set(Calendar.DAY_OF_MONTH, 4);

cal.set(Calendar.YEAR, 2016);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

assertEquals(Calendar.FRIDAY, dayOfWeek);


Java 8

LocalDate date = LocalDate.of(2016, Month.APRIL, 4);

DayOfWeek dayOfWeek = date.getDayOfWeek();

assertEquals(DayOfWeek.FRIDAY, dayOfWeek);

또는 

int dayOfWeek2 = dayOfWeek.get(ChronoField.DAY_OF_WEEK);

assertEquals(DayOfWeek.FRIDAY.getValue(), dayOfWeek2);

또는    

LocalDateTime localDateTime = LocalDateTime.of(2016, Month.APRIL, 4, 5, 4);

DayOfWeek dayOfWeek3 = localDateTime.getDayOfWeek();

assertEquals(DayOfWeek.FRIDAY, dayOfWeek3);


Joda Time

DateTime dateTime = new DateTime(2016, 4, 4, 0, 0);

int dayOfWeek = dateTime.getDayOfWeek();

assertEquals(DateTimeConstants.FRIDAY, dayOfWeek);


Old JDK

int day = 2;
DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ENGLISH);
System.out.println(dfs.getWeekdays()[day % 7 + 1]);




반응형

반응형

스프링 비동기와 자바8의 CompletableFuture Spring Async and Java’s 8 CompletableFuture


아래는 '비동기' 유저찾기 메소드의 예제의 구현이다. (전체 소스는 여기)

1@Async
2public Future<User> findUser(String user) throws InterruptedException {
3  System.out.println("Looking up " + user);
4  User results = restTemplate.getForObject("https://api.github.com/users/" + user, User.class);
5  // Artificial delay of 1s for demonstration purposes
6  Thread.sleep(1000L);
7  return new AsyncResult<User>(results);
8}

나는 왜 여전히 'Future'가 이 예제에 있는지 궁금했다. 나는 원작자가 이미 자바8의 새로운 CompletableFuture가 있는 걸 알고 있지만, 아마 자바 6나 7과의 이전 버전 호환성을 고려해서 남겨두었다고 생각했다.

여기있는 매우 정갈한 예제를 보면 이러한 의문을 가진건 나 혼자만은 아닌것 같다. 이 글의 답글 중 하나에서, 당신은 스프링 API 버전 4.2 에 포함되어 있는 힌트 - 이미 지원하고 있는 Future와 AsyncResult에서 CompletableFuture를 사용이 호환가능하다는 를 볼 수 있을 것이다. 나는 '누군가가 이 예제를 돌리면 그는 아마 현재의 구현에 머무를 것이므로 직접 적용해보거나 문서화 하지않는 것은 부끄러운 일이다'라는 생각이 들었다. 표준화된 방법을 사용하지않을 이유가 없다.

그래서 나는 Future를 지우고 CompletableFuture로 바꾸는 작은 수정을 하기로 했다. 또한 Future.isDone() 구문을 주석처리하고  CompletableFuture.allof() 메소드로 대체할 것이다.

또한 호출자 코드를 업데이트하면서 3개의 future 들을 동기화하도록 'service' 메소드의 리턴타입을 바꿨다. 일단 allof() 모두 완료되면 우리는 결과를 출력할 수 있다.

01package hello;
02 
03import java.util.concurrent.CompletableFuture;
04import java.util.concurrent.Future;
05 
06import org.springframework.scheduling.annotation.Async;
07import org.springframework.scheduling.annotation.AsyncResult;
08import org.springframework.stereotype.Service;
09import org.springframework.web.client.RestTemplate;
10 
11@Service
12public class GitHubLookupService {
13 
14    RestTemplate restTemplate = new RestTemplate();
15 
16    @Async
17    public CompletableFuture findUser(String user) throws InterruptedException {
18        System.out.println("Looking up " + user);
19        User results = restTemplate.getForObject("https://api.github.com/users/" + user, User.class);
20        // Artificial delay of 1s for demonstration purposes
21        Thread.sleep(1000L);
22        return CompletableFuture.completedFuture(results);
23    }
24 
25}

이 수정된 예제는 여기서 받을 수 있다. 나는 Tomasz Nirkewicz의 블로그에서 CompletableFuture의 풍부한 메소드 리스트를 매우 실용적이고 멋있게 설명한 이 글이 글을 찾았다. 또한 매우 완벽한 프리젠테이션도 여기서 받을 수 있다.


01@Override
02    public void run(String... args) throws Exception {
03        // Start the clock
04        long start = System.currentTimeMillis();
05 
06        // Kick of multiple, asynchronous lookups
07        CompletableFuture page1 = gitHubLookupService.findUser("PivotalSoftware");
08        CompletableFuture page2 = gitHubLookupService.findUser("CloudFoundry");
09        CompletableFuture page3 = gitHubLookupService.findUser("Spring-Projects");
10 
11        // Wait until they are all done
12        //while (!(page1.isDone() && page2.isDone() && page3.isDone())) {
13          //  Thread.sleep(10); //10-millisecond pause between each check
14        //}
15 
16        //wait until all they are completed.
17        CompletableFuture.allOf(page1,page2,page3).join();
18        //I could join as well if interested.
19 
20        // Print results, including elapsed time
21        System.out.println("Elapsed time: " + (System.currentTimeMillis() - start) +" ms");
22        System.out.println(page1.get());
23        System.out.println(page2.get());
24        System.out.println(page3.get());
25    }



반응형

반응형

스프링에서 @Async로 비동기처리하기 @Async in Spring

[원문: http://www.baeldung.com/spring-async]


1. 개요 Overview

이 글에서 스프링의 비동기 실행 지원asynchronous execution support과 @Async annotation에 대해 살펴볼 것이다. 간단히 설명하면, @Async 어노테이션을 빈bean에 넣으면 별도의 쓰레드에서 실행되는 것이다. 이를테면 호출자는 호출된 메소드가 완료될 때까지 기다릴 필요가 없다.



2. Async 기능 켜기 Enable Async Support

자바 설정Java configuration으로 비동기 처리enabling asynchronous processing를 쓰려면 간단히 설정 클래스에 @EnableAsync를 추가해주기만 하면 된다:

1
2
3
@Configuration
@EnableAsync
public class SpringAsyncConfig { ... }

위의 어노테이션이면 충분하지만, 당신이 필요로 하는 몇가지 옵션 또한 설정해 줄 수 있다:

  • annotation – 기본값, @EnableAsync은 스프링의 Async 어노테이션을 감지하며 EJB 3.1javax.ejb.Asynchronous; 이 옵션으로 사용자 정의된 다른 어노테이션 또한 감지할 수 있다.
  • mode – 사용해야할 advice의 타입을 가르킨다 - JDK proxy 기반 또는 AspectJ weaving.
  • proxyTargetClass – 사용해야할 proxy의 타입을 가르킨다 - CGLIB 또는 JDK; 이 속성값은 오직 mode가 AdviceMode.PROXY 로 설정되어 있을때만 유효하다.
  • order – sets the order in which AsyncAnnotationBeanPostProcessor 가 적용해야할 순서를 설정한다; 단지 모든 현존의 프록시를 고려하기 위해 기본값으로 마지막부터 실행된다.

비동기 처리는 task 네임스페이스를 사용하여 XML 설정을 통해 사용할 수도 있다:

1
2
<task:executor id="myexecutor" pool-size="5"  />
<task:annotation-driven executor="myexecutor"/>

3. @Async 어노테이션 The @Async Annotation

먼저 규칙을 살펴보자 – @Async 는 두가지 제약사항이 있다:

  • 1. public 메소드에만 적용해야한다
  • 2. 셀프 호출self invocation – 같은 클래스안에서 async 메소드를 호출 – 은 작동하지않음

이 이유는 간단한데 메소드가 public이어야 프록시가 될수 있기 때문이고 셀프호출은 프록시를 우회하고 해당 메소드를 직접 호출하기때문에 작동하지않는 것이다.


3.1. 리턴타입이 없는 메소드 Methods with void Return Type

다음과 같이 간단한 설정으로 리턴타입이 void인 메소드가 비동기로 작동한다:

1
2
3
4
5
@Async
public void asyncMethodWithVoidReturnType() {
    System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
}

3.2. 리턴타입이 있는 메소드 Methods with Return Type

Future 객체에 실제 리턴값을 넣음으로서 @Async 는 리턴타입이 있는 메소드에 적용할 수 있다.can also be applied to a method with return type:

1
2
3
4
5
6
7
8
9
10
11


@Async
public Future<String> asyncMethodWithReturnType() {
    System.out.println("Execute method asynchronously - " + Thread.currentThread().getName());
    try {
        Thread.sleep(5000);
        return new AsyncResult<String>("hello world !!!!");
    } catch (InterruptedException e) {
        //
    }
    return null;
}

스프링은 또한 Future를 구현한 AsyncResult 클래스를 제공하며 이는 비동기 메소드 실행의 결과를 가져오는데 사용한다.

이제 위의 메소드를 호출하여 Future 객체를 사용해 비동기 처리의 결과값을 가져와보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void testAsyncAnnotationForMethodsWithReturnType()
    throws InterruptedException, ExecutionException {
    System.out.println("Invoking an asynchronous method. "
      + Thread.currentThread().getName());
    Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();
 
    while (true) {
        if (future.isDone()) {
            System.out.println("Result from asynchronous process - " + future.get());
            break;
        }
        System.out.println("Continue doing something else. ");
        Thread.sleep(1000);
    }
}

4. 실행자 The Executor

스프링은 기본값으로 SimpleAsyncTaskExecutor 를 사용하여 실제 메소드들을 비동기 실행한다. 기본 설정은 두가지 레벨로 오버라이드할 수 있다 - 어플리케이션 레벨 또는 개인 메소드 레벨.


4.1. 메소드 레벨로 실행자 오버라이드하기 Override the Executor at the Method Level

설정 클래스에서 필요한 실행자를 선언해주어야한다:

1
2
3
4
5
6
7
8
9
@Configuration
@EnableAsync
public class SpringAsyncConfig {
     
    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

그 후 실행자 이름을 @Async에서 속성값으로 제공해주어야 한다:

1
2
3
4
5
@Async("threadPoolTaskExecutor")
public void asyncMethodWithConfiguredExecutor() {
    System.out.println("Execute method with configured executor - "  + Thread.currentThread().getName());
}

4.2. 어플리케이션 레벨로 실행자 오버라이드하기 Override the Executor at the Application Level

이 경우 설정 클래스는AsyncConfigurer 인터페이스를 구현해주어야한다 - 이는 getAsyncExecutor() 메소드를 구현해야한다는 의미이다. 여기에 우리는 전체 어플리케이션을 위한 실행자를 리턴할 것이다 - 이는 이제 @Async로 어노테이션된 메소드를 실행하는 기본 실행자가 된다.

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
     
    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolTaskExecutor();
    }
     
}

5. 예외 처리하기 Exception Handling

메소드의 리턴타입이 Future일 경우 예외처리는 쉽다 - Future.get() 메소드가 예외를 발생한다.

하지만 리턴타입이 void일 때, 예외는 호출 스레드에 전달되지 않을 것이다. 따라서 우리는 예외 처리를 위한 추가 설정이 필요하다.

우리는 AsyncUncaughtExceptionHandler 인터페이스를 구현함으로서 커스텀 비동기 예외처리자를 만들것이다. handleUncaughtException() 메소드는 잡히지않은uncaught 비동기 예외가 발생할때 호출된다:

1
2
3
4
5
6
7
8
9
10
11
12
public class CustomAsyncExceptionHandler  implements AsyncUncaughtExceptionHandler {
 
    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
        System.out.println("Exception message - " + throwable.getMessage());
        System.out.println("Method name - " + method.getName());
        for (Object param : obj) {
            System.out.println("Parameter value - " + param);
        }
    }
     
}

전 섹션에서 우리는 설정 클래스에 의해 구현된 AsyncConfigurer 인터페이스를 보았다. 그 일부로서 우리의 커스텀 비동기 예외처리자를 리턴하는 getAsyncUncaughtExceptionHandler() 메소드 또한 오버라이드해주어야한다:

1
2
3
4
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return new CustomAsyncExceptionHandler();
}

6. 결 론 Conclusion

이 튜토리얼에서 우리는 스프링에서 비동기 코드를 동작하는 법을 둘러보았다. 매우 기본적인 설정과 어노테이션으로 작동해 보았을 뿐 아니라, 우리가 설정한 실행자, 또는 예외처리 전략과 같은 더 고급진 설정법 또한 둘러보았다.






반응형

반응형

스프링 부트와 OAuth2

Spring Boot And OAuth2

(원문소스: https://spring.io/guides/tutorials/spring-boot-oauth2/)

Authorization 서버 돌리기 Hosting an Authorization Server

이 섹션에서 우리는 우리가 만들 앱을 여전히 페이스북과 Github을 사용하여 인증이 가능하지만 스스로 억세스 토큰을 만들 수 있는 완전무결fully-fledged한 OAuth2 인가서버Authorization Server로 만들도록 수정할 것이다. 이들 토큰은 이후 보호된secure 백엔드 리소스에서 사용되거나 똑같은 방식으로 보호되고 있는 다른 어플리케이션과의 SSO를 하는데 쓸 수 있다.

인증 설정을 정리하기 Tidying up the Authentication Configuration

인가서버Authorization server 기능을 시작하기 전에, 우리는 두개의 외부 제공자를 위한 설정코드를 깔끔하게 정리해보자. ssoFilter() 메소드안의 몇몇 코드가 중복되어있으므로 이를 공유 메소드로 가져올 것이다:

SocialApplication.java
private Filter ssoFilter() {
  CompositeFilter filter = new CompositeFilter();
  List<Filter> filters = new ArrayList<>();
  filters.add(ssoFilter(facebook(), "/login/facebook"));
  filters.add(ssoFilter(github(), "/login/github"));
  filter.setFilters(filters);
  return filter;
}

예전 메소드의 중복된 코드를 가지는 새로운 편리한 메소드이다:

SocialApplication.java
private Filter ssoFilter(ClientResources client, String path) {
  OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
      path);
  OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(client.getClient(),
      oauth2ClientContext);
  facebookFilter.setRestTemplate(facebookTemplate);
  facebookFilter.setTokenServices(new UserInfoTokenServices(
      client.getResource().getUserInfoUri(), client.getClient().getClientId()));
  return facebookFilter;
}

앱의 최종 버전에서 별도의 @Beans으로 선언된OAuth2ProtectedResourceDetails 그리고 ResourceServerProperties를 합친  새로운 wrapper 객체 ClientResources를 사용하였다:

SocialApplication.java
class ClientResources {

  private OAuth2ProtectedResourceDetails client = new AuthorizationCodeResourceDetails();
  private ResourceServerProperties resource = new ResourceServerProperties();

  public OAuth2ProtectedResourceDetails getClient() {
    return client;
  }

  public ResourceServerProperties getResource() {
    return resource;
  }
}

이 Wrapper와 전에 사용한 같은 YAML 설정을 함께 사용할 수 있지만, 각각 제공자를 위한 단일 메소드를 가지게 되었다:

SocialApplication.java
@Bean
@ConfigurationProperties("github")
ClientResources github() {
  return new ClientResources();
}

@Bean
@ConfigurationProperties("facebook")
ClientResources facebook() {
  return new ClientResources();
}

인가서버 돌리기 Enabling the Authorization Server

우리가 우리의 앱에 OAuth2 인가서버를 돌리려는데, 최소한 몇몇 기본기능(하나의 클라이언트와 억세스토큰을 만드는 능력)으로 시작하려고 수많은 삽질을 할 필요없다, 하나의 인가서버Authorization Server는 종단의 묶음이상이하도 아니다. 이들은 스프링 MVC 핸들러로서 스프링 OAuth2에서 구현되었다. 우리는 이미 보호된secure 어플리케이션을 가지고 있기때문에, 실제로 @EnableAuthorizationServer 어노테이션을 추가해주기만 하면 된다:

SocialApplication.java
@SpringBootApplication
@RestController
@EnableOAuth2Client
@EnableAuthorizationServer
public class SocialApplication extends WebSecurityConfigurerAdapter {

   ...

}

이 곳에 새 어노테이션을 추가함으로서, 스프링 부트는 우리가 지원하고 싶은 OAuth2 클라이언트에 약간의 디테일만 제공해주면, 그에 필요한 종단을 설치하고 그들에 시큐리티 설정을 해줄 것이다:

application.yml
security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      scope: read,write
      auto-approve-scopes: '.*'

이 클라이언트는 우리가 외부제공자로서 필요한 facebook.client* and github.client* 와 동일하다. 외부제공자를 우리 앱에서 사용하기 위해 우리는 클라이언트 id 와 secret을 받아서 등록해 주어야 한다. 우리의 경우, 이미 스스로 똑같은 기능을 제공하고 있으기 때문에 작동확인을 위한 (최소한 하나의) 클라이언트가 필요하다.

우리는 모든 스쿠프와 정규식 매칭되는 auto-approve-scopes설정을 하였다. 이는 우리가 이 앱을 실제 시스템에 돌릴때는 필요하지않지만,  스프링 OAuth2가 우리의 사용자가 억세스 토큰을 요구할 때 설정된게 없다면 사용자에게 팝업을 띄울 대체자나 whitelabel 승인페이지 없이 빠르게 무언가를 동작할 수 있게 해준다. 토큰을 승인하는 명시적 승인절차를 추가하려면 UI를 제공하여 (/oauth/confirm_access위치의) whitelabel 버전을 대체해주어야 한다.

억세스토큰 받는 법 How to Get an Access Token

억세스 토큰은 이제 우리의 새 인가서버에서 사용이 가능하다. 토큰을 얻는 가장 간단한 방법은 "acme" 클라이언트로서 하나를 긁어오는 것이다. 앱을 실행하고 다음과 같이 curl을 보내면 이것을 확인할 수 있다:

$ curl acme:acmesecret@localhost:8080/oauth/token -d grant_type=client_credentials
{"access_token":"370592fd-b9f8-452d-816a-4fd5c6b4b8a6","token_type":"bearer","expires_in":43199,"scope":"read write"}

클라이언트 credential 토큰은 어떤한 환경하에서(이를테면 토큰 종단이 동작하는지 테스트하는 등) 유용하다. 하지만, 우리 서버의 모든 기능을 장점을 취하려면 사용자들이 토큰을 만들수 있게 해줘야한다. 우리 앱에 보통의 사용자 행동을 통해 토큰을 받으려면, 사용자를 인증할 수 있어야 한다. 앱이 시작할 때 로그를 주의깊게 살펴보면, 아마 기본 스프링부트 사용자 (Spring Boot User Guide 참고)를 위한 임의 패스워드에 대한 로그를 볼 수 있을 것이다. 당신은 이 패스워드를 "사용자" ID와 같이 사용하여 사용자 방식으로 토큰을 받을 수 있다:

$ curl acme:acmesecret@localhost:8080/oauth/token -d grant_type=password -d username=user -d password=...
{"access_token":"aa49e025-c4fe-4892-86af-15af2e6b72a2","token_type":"bearer","refresh_token":"97a9f978-7aad-4af7-9329-78ff2ce9962d","expires_in":43199,"scope":"read write"}

"…​"이 있는 곳을 실제 패스워드로 바꿔줘야한다. 이것을 "패스워드 승인password grant"라고 부르는데 억세스 토큰을 위해 사용자아이디와 패스워드를 교환하는 것이다. 패스워드 승인은 당신이 credential을 저장하거나 유효한지 확인할수 있는 로컬 사용자 데이터베이스를 가지고 있는 네이티브 또는 모바일 어플리케이션에 적합하다. 웹앱 또는 어떤 "소셜"로그인을 가진 앱에서는 "인가코드 승인authorization code grant"이 필요하다. 이는 리다이렉트를 처리하기 위해 그리고 외부제공자로부터 사용자 인터페이스를 랜더할수 있는 브라우저가 필요하다는 의미이다.

클라이언트 어플리케이션 만들기 Creating a Client Application

우리 인가서버를 위한 클라이언트 어플리케이션은 그 자체로 하나의 웹어플리케이션이다. 스프링 부트로 손쉽게 만들수 있는데 다음 예제를 보자:

ClientApplication.java
@EnableAutoConfiguration
@Configuration
@EnableOAuth2Sso
@RestController
public class ClientApplication {

	@RequestMapping("/")
	public String home(Principal user) {
		return "Hello " + user.getName();
	}

	public static void main(String[] args) {
		new SpringApplicationBuilder(ClientApplication.class)
				.properties("spring.config.name=client").run(args);
	}

}

클라이언트를 위한 요소들은 (단지 사용자의 이름을 출력하는) 하나의 홈페이지와 (spring.config.name=client를 통한) 설정파일을 위한 명시적 이름이다. 우리가 이 앱을 돌리면 우리가 다음과 같이 제공한 설정파일을 찾을 것이다:

client.yml
server:
  port: 9999
security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      user-info-uri: http://localhost:8080/me

이 설정은 우리가 메인 앱에서 사용한 값들과 거의 비슷한 것 같지만, 페이스북이나 Github 대신에 "acme" 클라이언트를 가진다. 이 앱은 메인 앱과의 충돌을 피하기 위해 9999포트를 통해 동작되며 우리가 아직 구현하지 않은 사용자 정보 종단인 "/me"를 참조한다.

사용자 정보 종단 보호하기 Protecting the User Info Endpoint

우리가 페이스북과 Github을 사용한 것과 같이 새 인가서버에서 싱글사인온을 사용하려면, 생성된 억세스 토큰에 의해 보호되는 /user 종단을 만들어줘야한다. 지금까지 우리는 /user 종단을 가지고 있었고 사용자가 인증할 때 만들어진 쿠키에 의해 보호되고 있었다. 이를 추가적으로 로컬에서 승인된 억세스 토큰으로 보호하려면, 현존의 종단을 재사용하여 새로운 경로로 alias를 만들어주면 된다:

SocialApplication.java
@RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
  Map<String, String> map = new LinkedHashMap<>();
  map.put("name", principal.getName());
  return map;
}

 우리는 브라우저에 노출하고 싶지 않는 정보를 숨기기 위해, 또한 두개의 외부 인증 제공자사이의 종단의 행동을 구별하기 위해 Principal을 Map 으로 변환하였다. 원칙적으로 우리는 여기에 제공자의 구제적인 고유식별자 또는 만일 이용가능하다면 이메일과 같더 자세한 정보를 추가 할 수 있다.

이제 우리의 앱에 의해 만들어진 억세스 토큰에 보호되는 "/me" 경로는 (인가서버일 뿐아니라) 하나의 리소스 서버이다. 우리는 새 설정클래스를 만들었다. (메인앱의 n 내부 클래스로서, 하지만 이는 또한 별도의 독립실행가능한standalone 클래스로 나눌 수 있다.):

SocialApplication.java
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration
    extends ResourceServerConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .antMatcher("/me")
      .authorizeRequests().anyRequest().authenticated();
  }
}

추가적으로 우리는 메인 어플리케이션의 시큐티리를 위해 @Order를 명시해줘야한다:

SocialApplication.java
@SpringBootApplication
...
@Order(6)
public class SocialApplication extends WebSecurityConfigurerAdapter {
  ...
}

@EnableResourceServer 어노테이션은 기본값으로 @Order(3)를 가지는 시큐리티 필터를 만든다. 메인 어플리케이션 시큐리티를 @Order(6)로 옮김으로서 우리는 "/me"이 우선순위를 가지도록 보장해줄 수 있다.

OAuth2 클라이언트 테스트하기 Testing the OAuth2 Client

두개의 앱을 모두 동작시키고 브라우저오 127.0.0.1:9999를 방문하여 새 기능을 테스트해보자. 클라이언트 앱을 로컬 인가서버로 리다이렉트될 것이고 이후 사용자에게 페이스북이나 Github으로 인증을 선택하도록 할 것이다.  일단 테스트 클라이언트로 제어가 완전히 되돌아오면, 로컬 억세스 토큰은 승인되고 인증이 완료된다. (브라우저에서 "Hello" 메시지를 볼 수 있을 것이다). 만인 이미 Github이나 페이스북으로 인증이 되어있다면 이 원격 인증을 아마 알아차리지 못했을 것이다.

 테스트 클라이언트 앱에서 "localhost"를 사용하지 말자. 이는 메인 앱으로부터 쿠키를 빼앗아오기 때문에 인증이 엉망이 되어버린다. 만일 127.0.0.1이 "localhost"와 매핑되어 있지 않으면, 당신은 당신의 OS에서 이를 설정해주어야한다. (이를테면 "/etc/hosts") 또는 만일 있다면 다른 로컬 주소를 사용하자.

비인증 사용자를 위한 에러페이지 추가하기 Adding an Error Page for Unauthenticated Users

이 섹션에서 우리는 이전에 만든 Github 인증으로 전환하는 logout 앱을 수정하여 인증받지 못한 사용자를 위한 약간의 처리를 추가해볼 것이다. 동시에 우리는 특정 Github 조직에 속해있는 사용자들만 인증하도록 허용하는 규칙을 포함하도록 인증로직을 확장해 볼 것이다. "조직organization"은 Github만의 특정 개념이지만 유사한 규칙을 이를테면 구글같은 당신이 특정 도메인으로부터의 사용자만을 인증하도록 다른 제공자에게 적용할 수 있다

Github으로 전환하기 Switching to Github

logout 예제는 OAuth2 제공자로서 페이스북을 사용했다. 우리는 이를 로컬 설정을 수정함으로서 손쉽게 Github으로 전환할 수 있다:

application.yml
security:
  oauth2:
    client:
      clientId: bd1c0a783ccdd1c9b9e4
      clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
      accessTokenUri: https://github.com/login/oauth/access_token
      userAuthorizationUri: https://github.com/login/oauth/authorize
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://api.github.com/user

클라이언트에서 인증실패 감지하기 Detecting an Authentication Failure in the Client

클라이언트에서 우리는 인증하지 못한 사용자들에게 약간의 피드백을 제공해주려고 한다. 이를 제공해주려고 우리는 정보 메시지를 가진 div를 추가하였다:

index.html
<div class="container text-danger" ng-show="home.error">
There was an error (bad credentials).
</div>

이 텍스트는 컨트롤러에서 "error'플래그가 설정되었을때만 보여진다. 이를 위해 다음과 같이 약간의 코드가 필요하다:

index.html
angular
  .module("app", [])
  .controller("home", function($http, $location) {
    var self = this;
    self.logout = function() {
      if ($location.absUrl().indexOf("error=true") >= 0) {
        self.authenticated = false;
        self.error = true;
      }
      ...
    };
  });

"home" 컨트롤러는 브라우저가 로드될때 그 위치를 체크한다. 만일 URL에 "error=true"가 있다면 플래그가 설정된다.

에러페이지 추가하기 Adding an Error Page

클라이언트에서 플래그설정을 지원하기 위해 인증에러를 잡아내서 쿼리 파라메터안에 설정된 이 플래그를 가진 홈페이지로 리다이렉트할 수 있어야한다. 따라서 우리는 다음과 같은 보통의 @Controller내에 하나의 종단이 필요하다:

SocialApplication.java
@RequestMapping("/unauthenticated")
public String unauthenticated() {
  return "redirect:/?error=true";
}

이 예제 앱에서 우리는 메인 어플리케이션 클래스에 이것을 넣어주었다. 이제 이는 @RestController가 아니라 @Controller로 바꿔줌으로서 이제 리다이렉트를 처리할 수 있다. 우리가 마지막으로 해주어야할 것은 비인증 응답(UNAUTHORIZED로 알려진 HTTP 401)을 "/unauthenticated" 종단으로매핑해주는 것이다. 그냥 다음과 같이 추가해주면 된다:

ServletCustomizer.java
@Configuration
public class ServletCustomizer {
  @Bean
  public EmbeddedServletContainerCustomizer customizer() {
    return container -> {
      container.addErrorPages(
          new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
    };
  }
}

(이 예제에선, 단지 간결함을 위해 이는 메인 클래스 안에 내장된 클래스nested class로서 추가된다)

서버에서 401 만들기 Generating a 401 in the Server

401 응답은 사용자가 Github으로 로그인 안하거나 못할 경우 이미 스프링 시큐리티로 부터 보내지고 있다. 따라서 앱은 사용자가 인증에 실패할 경우 이미 동작하고 있는 것이다. (예를 들어, 토큰승인을 거절함으로서)

여기에 양념을 조금 더 쳐서, 우리는 인증 규칙을 확장하여 올바른 "조직"에 속해있지않은 사용자의 인증을 거부할 것이다. 사용자에 대해 더 많은 정보는 Github API를 사용하면 쉽다. 우리는 단지 인증 처리의 올바를 부분에 이것을 플러그해주기만 하면 된다. 운좋게도 이러한 간단한 사용예를 위해 스프링 부트는 손쉬운 확장점을 제공해주고 있다: 만일 우리가 타입 AuthoritiesExtractor @Bean을 선언해주면, 이는 인증된 사용자의 인가Authorities (보통은 "역할roles")를 구성하는데 사용될 것이다. 우리는 사용자가 올바른 조직에 속해있는지 확인하는데 사용할 수 있으면, 아닐 경우 예외가 발생한다:

SocialApplication.java
@Bean
public AuthoritiesExtractor authoritiesExtractor(OAuth2RestOperations template) {
  return map -> {
    String url = (String) map.get("organizations_url");
    @SuppressWarnings("unchecked")
    List<Map<String, Object>> orgs = template.getForObject(url, List.class);
    if (orgs.stream()
        .anyMatch(org -> "spring-projects".equals(org.get("login")))) {
      return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
    }
    throw new BadCredentialsException("Not in Spring Projects origanization");
  };
}

우리가 이 메소드안에 OAuth2RestOperations을 autowired했다는걸 기억하자, 우리는 이를 인증받은 사용자의 행동을 위한 Github API에 접근하는데 사용할 수 있다. 우리는 이렇게 하여 (스프링 오픈소스 프로젝트를 저장하는데 사용되는 조직인) "spring-projects"와 매치되는 조직들중 하나를 찾는다. 당신이 스프링 엔지니어링 팀의 일원이 아니라면 성공적으로 인증을 받기 위해 당신 자신의 값으로 대체하면 된다. 매치되는 값이 없다면 BadCredentialsException 예외가 발생하여 스프링 시큐리티가 이를 받아서 401 응답을 낸다.

 명맥하게 위의 코드는 어떤것은 Github에, 어떤것은 다른 OAuth2제공자에게 적용하도록 다른 인증 규칙로 일반화할 수 있다. 당신이 필요한건 제공자의 API에 대한 약간의 지식과 OAuth2RestOperations이 전부다.

결 론 Conclusion

우리는 스프링 부트와 스프링 시큐리티를 사용하여 최소한의 노력으로 수많은 스타일을 가진 앱을 만드는 법을 보아왔다. 모든 예제를 통해 작동하는 주요 테마는 외부 OAuth2 제공자를 사용하는 "소셜"로그인이다. 마지막 예제조차 "내부적으로" 그러한 서비스를 제공하는데 사용된다. 왜냐하면 이는 외부 제공자들이 가지고 있는 동일한 기본기능을 가지기 때문이다. 모든 예제 앱들은 더욱 구체적인 사용예를 위해 손쉽게 확장하고 재설정이 가능한데 보통은 하나의 설정파일을 수정하는것 이상도 이하도 아니다. 만일 당신이 페이스북이나 Github (또는 유사한) 제공자를 통해 등록하기하고 자신의 호스트 주소에 클라이언트 credentials을 얻으려면 자신만의 서버 버전을 사용해야한다는 것을 기억하자 또한 이들 credential을 소스컨트롤에 올리는 일이 없도록 주의하자!


반응형

반응형

스프링 부트와 OAuth2

Spring Boot And OAuth2

(원문소스: https://spring.io/guides/tutorials/spring-boot-oauth2/)

OAuth2 클라이언트의 수동설정 Manual Configuration of OAuth2 Client

이 섹션에서 우리는 @EnableOAuth2Sso 어노테이션의 '마법'으로 이미 만들어본  logout 앱을 모든 설정을 명시적으로 직접 설정하도록 수정해볼 것이다.

클라이언트와 인증 Clients and Authentication

 @EnableOAuth2Sso에는 OAuth2 클라이언트와 인증의 2가지 기능이 있다. 클라이언트는 재사용이 가능하고, 또한 당신의 인가서버Authorization Server (우리의 경우 페이스북)가 제공하는(우리의 경우 Graph API) OAuth2 리소스들과 상호작동하는데 사용할 수 있다. 이 인증 기능은 당신의 앱을 스프링시큐리티와 맞도록 맞춰준다. 일단 페이스북과 소통하는게 끝나면, 당신의 앱은 정확히 다른 보호된 스프링 앱secure Spring app과 똑같이 동작할 것이다.

클라이언트 

클라이언트 부분은 스프링 시큐리티 OAuth2에 의해 제공되며 @EnableOAuth2Client라는 다른 어노테이션을 쓴다. 따라서 이 수정의 첫 걸음은 @EnableOAuth2Sso를 삭제하고 더 낮은 레벨의 어노테이션으로 변경하는 것이다:

SocialApplication
@SpringBootApplication
@EnableOAuthClient
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {
  ...
}

일단 이렇게 하면 우리는 우리를 위해 만들어진 유용한 몇가지 기능을 가지게 된다. 먼저 OAuth2ClientContext를 주입할 수 있어, 우리의 시큐리티 설정에 추가할 인증 필터를 만드는데 쓸 수 있다:

SocialApplication
@SpringBootApplication
@EnableOAuthClient
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

  @Autowired
  OAuth2ClientContext oauth2ClientContext;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/**")
      ...
      .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
  }

  ...

}

이 필터는 우리가 OAuth2ClientContext를 사용하는 새 메소드에서 생성된다:

SocialApplication
private Filter ssoFilter() {
  OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
  OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
  facebookFilter.setRestTemplate(facebookTemplate);
  facebookFilter.setTokenServices(new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
  return facebookFilter;
}

이 필터 역시 페이스북에 등록된 클라이언트 설정에 대해 알아야한다:

SocialApplication
  @Bean
  @ConfigurationProperties("facebook.client")
  OAuth2ProtectedResourceDetails facebook() {
    return new AuthorizationCodeResourceDetails();
  }

그리고 인증을 완료하려면 페이스북의 사용자 정보 종단user info endpoint이 어딘지 알아야 한다:

SocialApplication
  @Bean
  @ConfigurationProperties("facebook.resource")
  ResourceServerProperties facebookResource() {
    return new ResourceServerProperties();
  }

이 두개의 "정적인" 데이터 객체(facebook()과 facebookResource())에 우리가  @ConfigurationProperties. 로 설정된 @Bean 을 사용했다는 것을 알아두자. 이것은 우리가 application.yml를, 설정의 접두어를 security.oauth2대신 facebook로 사용하는 약간 새로운 포멧으로 전환할 수 있다는 것을 의미한다:

application.yml
facebook:
  client:
    clientId: 233668646673605
    clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
    accessTokenUri: https://graph.facebook.com/oauth/access_token
    userAuthorizationUri: https://www.facebook.com/dialog/oauth
    tokenName: oauth_token
    authenticationScheme: query
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://graph.facebook.com/me

리다이렉트 처리하기 Handling the Redirects

마지막 수정은 우리의 앱에서 페이스북으로 리다이렉트를 명시적으로 지원하게 만들어주는 것이다. 이는 서블릿 Filter를 가진 Spring OAuth2에서 처리되어진다. 이 필터는 어플리케이션 컨텍스트application context에서 이미 사용가능한데 우리가 @EnableOAuthClient선언을 해두었기 때문이다. 우리가 이 필터를 엮어서 사용하려면 그냥 스프링부트 어플리케이션의 올바른 순서right order안에서 호출해 주기만 하면 된다. 이것을 위해 우리는 FilterRegistrationBean이 필요하다:

SocialApplication.java
@Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(
    OAuth2ClientContextFilter filter) {
  FilterRegistrationBean registration = new FilterRegistrationBean();
  registration.setFilter(filter);
  registration.setOrder(-100);
  return registration;
}

우리는 이미 사용가능할 필터를 Autowire해두었고, 이 필터를 메인 스프링 시큐리티 필터가 불러지기 전에 호출되도록 충분히 낮은 순서로 등록하였다. 이 방법으로 우리는 인증요청의 예외exception발생을 통해 리다이렉트를 처리할 수 있다.

이 단계까지의 수정을 통해 앱은 동작이 가능하며, 실행시 지난 섹션에서 만드 logout예제와 동일하게 동작한다. 설정을 단계별로 쪼개고 몇시적으로 우리에게 가르쳐줌으로서 스프링 부트가 해주는 마법과 같은 자동화는 더이상 없다. (이는 단지 설정의 뼈대일 뿐이다). 그리고 이는 막바로 사용가능하게 자동으로 제공되었던 기능을 확장하기 위한, 우리 자신의 의사과 비지니스 요구사항을 추가하기 위한 준비가 된다.

Github으로 로그인하기 Login with Github

이 섹션에서 우리가 이미 페이스북 링크를 통해 로그인이 가능했던 앱을 Github 인증을 추가하여 사용자가 선택할 수 있는 링크를 추가하도록 기존의 app을 수정할 것이다. 

Github 링크 추가하기 Adding the Github Link

클라이언트에서의 수정은 매우 사소하다. 단지 또다른 링크만 추가해주면 된다:

index.html
<div class="container" ng-show="!home.authenticated">
  <div>
    With Facebook: <a href="/login/facebook">click here</a>
  </div>
  <div>
    With Github: <a href="/login/github">click here</a>
  </div>
</div>

원칙적으로, 일단 우리가 인증 제공자를 추가하려면 "/user" 종단으로부터 되돌아오는 데이터에 대해 더 신중해져야 한다. Github과 페이스북 둘다 사용자 정보안에 "name"필드가 똑같이 있다. 따라서 우리의 종단에 실제로 수정을 해줄 필요가 없다.

Github 인증필터 추가하기 Adding the Github Authentication Filter

서버단의 주요 수정은 우리의 새 링크로 부터 오는 "/login/github" 요청을 처리하는 부가적인 시큐리티 필터를 추가하는 것이다. 이미 우리는 ssoFilter() 메소드에서 만들어진 페이스북을 위한 커스텀 인증 필터를 가지고 있으므로, 인증 경로를 하나이상 처리할 수 있도록 그냥 기존의 것을 Composite필터를 써서 바꿔주기만 하면 된다

SocialApplication.java
private Filter ssoFilter() {

  CompositeFilter filter = new CompositeFilter();
  List<Filter> filters = new ArrayList<>();

  OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
  OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
  facebookFilter.setRestTemplate(facebookTemplate);
  facebookFilter.setTokenServices(new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
  filters.add(facebookFilter);

  OAuth2ClientAuthenticationProcessingFilter githubFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github");
  OAuth2RestTemplate githubTemplate = new OAuth2RestTemplate(github(), oauth2ClientContext);
  githubFilter.setRestTemplate(githubTemplate);
  githubFilter.setTokenServices(new UserInfoTokenServices(githubResource().getUserInfoUri(), github().getClientId()));
  filters.add(githubFilter);

  filter.setFilters(filters);
  return filter;

}

우리의 예전 ssoFilter()의 코드는 하나는 페이스북, 다른 하나는 Github용으로 중복된다. 이 두개의 필터는 하나의 컴포지트composite로 합쳐진다.

facebook()과 facebookResource() 메소드 역시 유사하게 github()과 githubResource()로 추가해줘야한다:

SocialApplication.java
@Bean
@ConfigurationProperties("github.client")
OAuth2ProtectedResourceDetails github() {
	return new AuthorizationCodeResourceDetails();
}

@Bean
@ConfigurationProperties("github.resource")
ResourceServerProperties githubResource() {
	return new ResourceServerProperties();
}

그리고 이에 상응하는 설정들 역시 추가해준다:

application.yml
github:
  client:
    clientId: bd1c0a783ccdd1c9b9e4
    clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
    accessTokenUri: https://github.com/login/oauth/access_token
    userAuthorizationUri: https://github.com/login/oauth/authorize
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://api.github.com/user

여기의 클라이언트 디테일들은 Github에 등록된 정보여야 하며 (페이스북과 동일하게) localhost:8080주소를 가르켜야한다.

앱은 이제 준비되었고 사용자가 페이스북 또는 Github으로 인증을 선택하도록 동작할 것이다.

로컬 사용자 데이터베이스를 추가하기 How to Add a Local User Database

많은 어플리케이션은 인증을 외부 제공자에의해 위임할 경우에도, 그들 사용자의 데이터를 로컬에서 가지고 있어야 한다. 여기에 그 코드를 보여주진 않을 것이지만 이를 쉽게 해주는 두가지 단계가 있다:

  1. 당신의 데이터베이스를 위한 백엔드를 선택한 후, 외부 인증으로부터 일부 또는 전체를 불러올 수 오는데 사용하는 커스텀 User 객체를 위한 (스프링 데이터 등을 사용하여) 리파지토리repository를 설정하라

  2. 당신의 /user 종단에서 리파지토리 검사에 의해 로그인된 각각 고유한 사용자를 위한  User 객체를 규정하자. 만일 현재의 Principal의 식별자를 가진 사용자가 이미 있다면, 업데이트하거나, 그렇지않다면 생성할 수 있다.

힌트: User 객체에 필드 하나를 추가하여 외부 제공자의 고유 식별자를 링크해주자 (사용자의 이름같은 게 아닌 무언가 고유한 것)


반응형

반응형

스프링 부트와 OAuth2

Spring Boot And OAuth2

(원문소스: https://spring.io/guides/tutorials/spring-boot-oauth2/)

기본페이지 추가하기 Add a Welcome Page

이 섹션에서 우리는 '페이스북에 로그인하기'라는 명시적 링크를 추가함으로서 방금 만든 simple앱을 수정할 것이다.  즉시 리다이렉트되는 대신, 새 링크는 홈페이지에 보여져 사용자가 로그인을 할지 안할지 선택할 수 있게 된다. 사용자가 링크를 클릭했을 때만 인증된 컨탠트가 보여질 것이다.

홈페이지의 조건적 컨탠트 Conditional Content in Home Page

어떠한 컨탠트를 사용자가 인증했을 때 또는 우리가 서버측 랜더링(이를테면 Freemaker또는 Thymeleaf)을 사용하지 않을지 조건적으로 랜더하거나 또는 자바스크립트를 조금 써서 우리가 그냥 브라우저에게 그것하라고 물어보게 할 수 있다. 이것을 위해 우리는 AngularJS를 쓸 것이다. 만약 당신이 선호하는 다른 프레임워크가 있다면 클라이언트 코드를 옮기는게 그다지 어렵지 않을 것이다.

앵귤러JS를 쓰기위해 우리는 앵귤러 앱 컨테이너로서 <body>에 마크해 주었다.

index.html
<body ng-app="app" ng-controller="home as home">
...
</body>

Body안의 <div> 엘리먼트들은 그것이 보여지는 부분들 제어하는 모델에 묶여bound질 수 있다.

index.html
<div class="container" ng-show="!home.authenticated">
	Login with: <a href="/login">Facebook</a>
</div>
<div class="container" ng-show="home.authenticated">
	Logged in as: <span ng-bind="home.user"></span>
</div>

이 HTML은 authenticated 플래그와 인증받은 사용자를 위한 user객체를 가진 "home" 컨트롤러를 필요로 한다. 여기 이들 기능의 간단한 구현체를 보자 (<body>)의 끝 줄에 이들을 넣자):

index.html
<script type="text/javascript" src="/webjars/angularjs/angular.min.js"></script>
<script type="text/javascript">
  angular.module("app", []).controller("home", function($http) {
    var self = this;
    $http.get("/user").success(function(data) {
      self.user = data.userAuthentication.details.name;
      self.authenticated = true;
    }).error(function() {
      self.user = "N/A";
      self.authenticated = false;
    });
  });
</script>

서버측 수정 Server Side Changes

이를 동작시키려면, 서버쪽에 약간 수정을 해줘야한다. "home" 컨트롤러는 현재 인증받은 사용자정보를 받아오는  "/user"라는 종단endpoint이 필요하다. 메인 클래스에서 다음과 같이 아주 쉽게할 수 있다:

SocialApplication
@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication {

  @RequestMapping("/user")
  public Principal user(Principal principal) {
    return principal;
  }

  public static void main(String[] args) {
    SpringApplication.run(SocialApplication.class, args);
  }

}

우리가 핸들러 메소드에 주입한 @RestController 와 @RequestMapping 그리고 java.util.Principal 등을 알아두자

위와 같이 /user 종단에 Principal 전체를 리턴하는 것은 매우 안좋은 발상이다. (브라우저 클라이언트에 노출해서는 안되는 정보를 포함하고 있기 때문이다.) 재빠른 동작을 위해 이렇게 했지만 이 가이드의 후반에 이 종단의 정보를 숨기도록 바꿀 것이다.

이 앱은 이제 사용자가 우리가 제공한 링크를 클릭함으로서 전처럼 인증할 수 있게 잘 동작할 것이다. 이 링크를 보이도록 만드려면 WebSecurityConfigurer를 추가하여 홈페이지의 보안을 꺼주어야 한다:

SocialApplication
@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

  ...

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .antMatcher("/**")
      .authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**")
        .permitAll()
      .anyRequest()
        .authenticated();
  }

}

스프링 부트는 @EnableOAuth2Sso 어노테이션을 가진 클래스의 WebSecurityConfigurer에 특별한 의미를 부여한다: OAuth2 authentication processor를 가진 시큐리티 필터체인security filter chain을 쓸 수 있도록 설정한다. 홈페이지를 보이도록 만드는 데 필요한건 홈페이지와 관련된 정적인 리소스를 authorizeRequests()에 명시하는 것이다. (우리는 인증을 다루는데 필요한 로그인 종단의 접근 또한 포함할 것이다.). 모든 이외의 요청들(예를 들어, /user종단) 인증이 필요하다.

이 단계의 수정을 거쳐 어플리케이션은 완성되었다. 서버를 돌리고 홈페이지를 방문하면 "Login with Facebook"이라는 멋지게 스타일된 HTML링크를 볼 수 있을 것이다. 이 링크는 당신을 페이스북으로 직접 가게해주는게 아니라, 인증을 처리하는 로컬 경로로 데려다준다.(그리고 페이스북으로 리다이렉트를 보낸다). 일단 인증을 받았다면, 로컬앱으로 다시 리다이렉트 되어, 이제 당신의 이름을 보여줄 것이다. ( 당신이 페이스북에 데이터접근을 허락한다고 설정했을 경우)

로그아웃 버튼 추가하기 Add a Logout Button

이 섹션에서 우리는 사용자가 앱을 로그아웃하도록 버튼을 추가함으로서 click 앱을 수정할것이다. 이는 간단한 기능같이 보일지 모르지만 사실 구현에 매우 신중해야한다. 정확히 어떻게 이렇게 하는지 약간의 시간을 들여 곱씹어볼 가치가 있다. 사실 대부분의 수정은 읽기 전용 리소스에서 읽고 쓰기가 가능한 리소스로 (로그아웃을 한다는 것은 상태변경을 해주어야한다) 앱을 변환하는 작업을 해주는 것이다. 단지 정적인 컨텐트가 아닌 어떤 실제 어플리케이션에서 같은 변경을 해주어야한다.

클라이언트측 변경 Client Side Changes

클라이언트에서 우리는 그냥 로그아웃 버튼과 자바스크립트로 서버에 인증을 취소할지 물어보는 호출만 제공해주기만 하면 된다. 먼저, UI의 "인증받은authenticated" 섹션에서 버튼을 추가하자: 

index.html
<div class="container" ng-show="home.authenticated">
  Logged in as: <span ng-bind="home.user"></span>
  <div>
    <button ng-click="home.logout()" class="btn btn-primary">Logout</button>
  </div>
</div>

그다음 logout() 함수를 제공하여 자바스크립트를 참조한다:

index.html
angular
  .module("app", [])
  .controller("home", function($http, $location) {
    var self = this;
    self.logout = function() {
      $http.post('/logout', {}).success(function() {
        self.authenticated = false;
        $location.path("/");
      }).error(function(data) {
        console.log("Logout failed")
        self.authenticated = false;
      });
    };
  });

logout() 함수는 /logout 로  POST 호출을 한뒤 authenticated 플래그를 초기화한다. 이제 우리는 종단의 구현을 위해 서버측으로 옮겨가보자.

로그아웃 종단 추가하기 Adding a Logout Endpoint

스프링 시큐리티는 우리가 하려고 하는 일(세션을 정리하고 쿠키를 무효화invalidate함)을 위한 /logout 종단 지원을 내장하고 있다. 이 종단을 설정하려면, 간단히 우리의 WebSecurityConfigurer에 있는 configure method 메소드를 다음과 같이 확장하면 된다:

SocialApplication.java
@Override
protected void configure(HttpSecurity http) throws Exception {
  http.antMatcher("/**")
    ... // existing code here
    .and().logout().logoutSuccessUrl("/").permitAll();
}

/logout종단은 우리에게 이 요청을 POST로 보낼것을 요구한다. 그리고 Cross Site Request Forgery (씨서프sea surf라 발음하는 CSRF)로 부터 사용자를 보호하기 위해 이 요청안에 하나의 토큰을 넣으라고 요구한다. 이 토큰의 값은 현재 세션으로 링크되어있는데 이는 무엇을 보호하는지 제공해주는 일을 한다. 이제 우리의 자바스크립트 앱에 이 데이터를 넣는 방법을 알아야한다.

앵귤러JS 또한 (그들이 XSRF라 부르는) CSRF 지원을 내장하고 있다. 하지만 스프링 시큐리티의 통상적인 방법과 약간 다르게 구현되어있다. 앵귤러가 서버에게 원하는 것은 "XSRF-TOKEN"이라 부르는 쿠키를 보내주는 것이다. 이것이 들어있으면 앵귤러는 "X-XSRF-TOKEN"이라는 이름의 헤더를 되돌려준다. 스프링 시큐리티에서 이것을 알려주기 위해, 우리는 쿠키를 만드는 필터를 하나 추가해주어야한다, 또한 현재의 CSRF 필터에 이 헤더이름을 알려주어야한다. WebSecurityConfigurer에서:

SocialApplication.java
@Override
protected void configure(HttpSecurity http) throws Exception {
  http.antMatcher("/**")
    ... // existing code here
    .and().csrf().csrfTokenRepository(csrfTokenRepository())
    .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}

csrfHeaderFilter()는 다음의 커스텀 필터이다:

SocialApplication.java
private Filter csrfHeaderFilter() {
  return new OncePerRequestFilter() {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
      CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
      if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
          cookie = new Cookie("XSRF-TOKEN", token);
          cookie.setPath("/");
          response.addCookie(cookie);
        }
      }
      filterChain.doFilter(request, response);
    }
  };
}

그리고 csrfTokenRepository()는 여기 정의되어있다.:

SocialApplication.java
private CsrfTokenRepository csrfTokenRepository() {
  HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
  repository.setHeaderName("X-XSRF-TOKEN");
  return repository;
}

출동준비완료! Ready To Roll!

여기까지의 수정으로, 우리는 서버를 동작하고 새로운 로그아웃 버튼을 시도할 준비를 마쳤다. 앱을 시작하고 새 브라우저 창에 홈페이지를 열어서 "login"링크를 클릭하면 당신을 페이스북으로 데려다 줄 것이다. (이미 로그인 되어있다면 아마 리다이렉트를 알아차리지 못할 것이다.). 현재 세션을 종료하기위해 "Logout"버튼을 클릭하면 앱은 비인증 상태로 되돌아 온다. 궁금하면 브라우저가 로컬서버에서 받아온 요청안에 새 쿠키와 헤더를 확인할 수 있을 것이다.

이제 브라우저 클라이언트에서 로그아웃 종단이 동작하는 것을 기억하자, 이제 모든 HTTP요청들((POST,PUT,DELETE,등등)에서 또한 잘 동작할 것이다. 이 앱은 이제 약간은 더 실전적 기능을 가진 좋은 플랫폼이 되었다.


반응형

반응형

스프링 부트와 OAuth2

Spring Boot And OAuth2

(원문소스: https://spring.io/guides/tutorials/spring-boot-oauth2/)


이 가이드에서 OAuth2와 Spring Boot를 사용해 어떻게 하면 "소셜 로그인"의 다양한 일을 하는 예제를 만들 수 있는 지 보여줄 것이다. 간단한 하나의 싱글사인온 제공자에 연결해보는 걸로 시작하여, Facebook 이나 Github과 같은 authentication 제공자와 함께 OAuth2 Authorization Server를 스스로 돌리는 일을 해볼것이다. 예제들은 백엔드로 모두 스프링 부트와 스프링 OAuth를 사용한 단일 페이지 앱이 될 것이며 프론트엔드로 모두 AngularJS 를 사용하였다. 하지만 자바스크립트단의 코드나 서버의 랜더링사용은 최소화 하였다.

각각 새로운 기능을 추가해놓은 몇가지 예제들이다:

  • simple: 매우 기본적인 정적 앱으로 그냥 하나의 홈페이지와 스프링부트의 @EnableOAuth2Sso를 통해 무작위 로그인을 한다 (홈페이지를 방문하면 자동으로 페이스북으로 리다이렉트 될 것이다)

  • click: 사용자가 로그인을 클릭할 수 있는 명시적 링크를 추가하였다.

  • logout: 인증받은 사용자를 위한 로그아웃 링크를 추가하였다.

  • manual @EnableOAuth2Sso 어노테이션을 사용하지않고 수동으로 설정하여 똑같이 동작시켜본다.

  • gitub: 두번째 로그인 제공자로서 Github을 추가하여 사용자는 홈페이지에서 어느것을 사용할 지 고를 수 있다.

  • auth-server스스로 토큰을 발행할 수 있지만 여전히 인증을 위해 외부 OAuth2 제공자를 사용할 수 있는 완전무결한fully-fledged OAuth2  Authorization 서버를 돌린다. 

  • custom-error Github API에 기반한 커스텀 인증과, 비인증 사용자를 위한 에러 메세지를 추가하였다.

이들은 각각 IDE에서 불러올 수 있으며, 앱을 시작할 수 있는 SocialApplication 메인 클래스가 있다. 이들 모두 http://localhost:8080 로 홈페이지에 접근할 수 있다.( 로그인을 하고 그 내용을 보려면 최소한 페이스북 계정이 필요하다). 또한, gmvn spring-boot:run를 사용하여 커맨드라인상에서 앱을 돌리거나, mvn package 를 통해 jar파일을 빌드하고 java -jar target/*.jar 로도 돌릴 수 있다. 프로젝트 상위레벨에 있는 wrapper를 사용하면 메이븐을 설치하지않다도 된다. 예를 들면:

$ cd simple
$ ../mvnw package
$ java -jar target/*.jar
 모든 앱은 localhost:8080

에서 동작한다. 페이스북과 Github에 이 주소로 OAuth2 클라이언트를 등록했기 때문이다. 다른 호스트나 포트로 돌리려면 스스로 각각 앱을 등록하고 config 파일에 해당 인증정보들을 넣어줘야한다. 기본설정값을 사용하면 localhost로 돌린다고 당신의 페이스북이나 Github 인증정보가 누출되거나 위험해지지않는다. 하지만 당신이 인터넷에 무엇을 노출할지 조심해야한다. 공개 소스 컨트롤에 당신의 앱을 등록하지 않아야한다.

페이스북으로 싱글 사인온 하기 Single Sign On With Facebook

이 섹션에서, 우리는 인증을 위해 페이스북을 사용하는 최소한의 어플리케이션을 만들것이다. 이는 스프링 부트의 자동설정을 사용하면 매우 쉽다. 

새 프로젝트 만들기

먼저 스프링 부트 어플리케이션을 만들어야 한다. 이를 위한 수많은 방법이 있지만, 가장 쉬운 것은 http://start.spring.io 를 방문하여 빈 프로젝트를 만드는 것이다. (시작점으로서 "Web" 의존성을 골라주자). 커맨드라인으로 아래와 같이하면 똑같이 만들 수 있다:

$ mkdir ui && cd ui
$ curl https://start.spring.io/starter.tgz -d style=web -d name=simple | tar -xzvf -

이제 당신이 선호하는 IDE에서 이 프로젝트를 불러올 수 있다. (기본적으로 보통의 메이븐 자바프로젝트다) 또는 파일 작업을 하고 그냥 커맨드라인에서 "mvn"을 사용해도 된다.

홈페이지 추가하기

새 프로젝트의 "src/main/resources/static" 폴더에 index.html파일을 만들자. 몇몇의 스타일시트와 자바스크립트를 링크해줘야하며 그 결과는 다음과 같다:

index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Demo</title>
    <meta name="description" content=""/>
    <meta name="viewport" content="width=device-width"/>
    <base href="/"/>
    <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
	<h1>Demo</h1>
	<div class="container"></div>
</body>
</html>

이 소스의 무엇도 OAuth2 로그인 기능과 무관하지만 우리는 홈페이지에 약간의 기본적인 기능을 시작할 수 있을 뿐아니라 멋지게 보이는 UI 를 원한다.

앱을 시작하고 홈페이지를 로드하면, 스타일 시트가 로드되지 않았다는 걸 알 수 있을 것이다. 이제 그들을 아래와 같이 의존성을 추가해줌으로서 해결할 수 있다:

pom.xml
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>angularjs</artifactId>
	<version>1.4.3</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>2.1.1</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>bootstrap</artifactId>
	<version>3.2.0</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>webjars-locator</artifactId>
</dependency>

우리는 트위터 부트스트랩과 (우리가 지금 당장 써야하는) jQuery, 거기에 나중에 쓸 AngularJS를 추가했다. 다른 의존성은 webjars "locator"로 webjars 사이트에 의해 라이브러리로서 제공받는 것이고 이것은 스프링에 의해 정확한 버전을 알 필요없이(그렇기 때문에 index.html에서 버전없는 /webjar/all}링크를 사용했다webjars의 정적인 어셋을 위치locate하는데 사용된다. 이 webjar locator를 활성화하려면 어플리케이션의 application.properties에서 Spring MVC 리소스 체인을 활성화시켜줘야한다:

application.properties
spring.resources.chain.enabled: true

이 수정을 통해 이제 우리는 이뻐보이는 홈페이지를 가지게 되었다.

어플리케이션 보호하기 Securing the Application

어플리케이션을 안전하게 만드려면, 스프링 시큐리티 의존성을 추가해주면 된다. 그러면 기본적으로 HTTP Basic으로 보호될 것이다. 따라서 우리가 (페이스북으로 위임하는) "소셜" 로그인을 만드려고 하므로, Spring Security OAuth2 의존성 또한 추가해줘야한다:

pom.xml
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.security.oauth</groupId>
	<artifactId>spring-security-oauth2</artifactId>
</dependency>

페이스북으로의 링크를 만드면, 메인클래스에서 @EnableOAuth2Sso 어노테이션을 해줘야한다:

SocialApplication.java
@SpringBootApplication
@EnableOAuth2Sso
public class SocialApplication {

  ...

}

그리고 약간의 설정이 필요하다 (더 나은 식별성을 위해 application.properties을 YAML 으로 변환하였다):

application.yml
security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me
...

이 설정은 페이스북의 개발자사이트에 등록된 클라이언트 앱을 참조한다. 당신은 당신의 앱에서 리다이렉트할 곳을 등록해줘야한다. (우리의 경우 Home page). 이것은 "localhost:8080"으로 등록되었는데, 이 주소로 돌아가는 앱에서만 작동한다.

이 수정으로 앱을 다시 돌리고 http://localhost:8080의 홈페이지를 방문해보자. 홈페이지 대신, 당신은 페이스북 로그인으로 리다이렉트될 것이다. 로그인하려고 인가authorization를 수락하면, 당신의 로컬 앱으로 다시 리다이렉트되어 돌아와지고 홈페이지가 보여질 것이다. 만일 페이스북 로그인이 되어있는 상태면, 브라우저를 완전히 새롭게 열어 쿠키도 없고 캐시된 데이터가 없더라고 이 로컬앱에서 재인증할 필요없다. (이것이 싱글사이온의 의미이다)

당신이 이 섹션의 예제 어플리케이션을 돌리는 중이라면, 브라우저의 쿠키와 HTTP Basic credentials의 캐시를 지웠는지 먼저 확인하자. 크롬의 incognito window를 사용하는 것이 가장 좋은 방법이다.

이 예제의 접근을 승인하는 것grant access은 안전하다. 로컬에서만 동작하고 있는 이 앱에서만 토큰을 사용할 수 있고 범위scope도 제약적이기 때문이다. 당신이 이와 같은 절차를 거치는 앱을 로그인할 때, 무엇을 승인해야하는지 반드시 살펴봐야한다: 당신이 불편해할 만큼의 권한을 요구할 수도 있기때문이다. (예를 들면, 당신의 개인정보를 수정할 수 있는 권한을 요구할 수 있다.)

방금 뭔일 있었나? What Just Happened?

당신이 방금 만든 이 앱은, OAuth2 용어로, 클라이언트 어플리케이션이다. 그리고 이 앱은 페이스북(인가서버Authorization Server)로부터 억세스토큰access token을 받기위해 authorization code grant를 사용했다. 그 후 당신의 로그인ID와 이름을 포함한 (당신이 허용해준) 몇가지 개인 정보를 페이스북에 요청하기 위해 억세스토큰을 사용했다. 이 단계까지 페이스북은 당신이 보낸 토큰을 디코딩하고 사용자의 정보에 접근하는 앱의 권한을 체크하는 등등의 리소스 서버로서 역할을 하고 있다. 이 단계가 성공적으로 완료되면, 당신의 앱은 사용자 정보를 스프링 시큐리티 컨텍스트Spring security context안에 넣음으로서 당신을 인증할 것이다.

(크롬의 F12누르면 보이는) 브라우저 도구를 열고 네트워크 트래픽을 따라가보면, 페이스북으로 리다이렉트되어 가고오고 하는것을 확인할 수 있으며 최종적으로 새 Set-Cookie 헤더를 가지고 홈페이지로 되돌아와진다. 이 쿠키(기본값으로JSESSIONID)는 스프링(또는 어느 서블릿 기반의) 어플리케이션에서 당신의 인증 상세정보를 위한 하나의 토큰이다.

이제 우리는, 어떠한 정보를 보기위해 사용자가 페이스북과 같은 외부 제공자로 인증해야하는 측면에서, 안전한 어플리케이션을 가지게 되었다. 우리는 웹사이트에 매번 이를 사용하려는게 아니라 기본 식별, 그리고 당신의 사이트에 서로 다른 사용자간에 컨텐트를 구별하기 위한 목적으로 이는 오늘날 이러한 종류의 인증이 왜 인기가 많은가를 설명하는 훌륭한 출발점이 될 것이다. 다음 섹션에서 우리는 어플리케이션에 약간의 기본 기능들을 추가하고, 사용자가 처음 페이스북으로 리다이렉트 할 때 언제 그리고 무엇을 하는지 조금더 구체적으로 알아볼 것이다.


반응형

반응형
스프링부트 : REST어플리케이션에서 예외처리하기

(원문소스: http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html)


기억할 점

스프링 부트 어플리케이션에서 예외처리하는 방법은 3가지다:

  1. 전역 처리 Global Level using -  @ControllerAdvice
  2. 컨트롤러단에서 처리 Controller Level using@ExceptionHandler 
  3. 메소드단위 처리 Method Level usingtry/catch  

REST 어플리케이션에서 예외처리하기 

예외처리를 테스트하기위에 3가지 예외를 만들것이다:

  • 모든 커스텀 예외의 부모가 될 BaseException.
  • Base Exception을 확장한 CustomException1.
  • Base Exception을 확장한 CustomException2.

다음의 메소드들을 만든다
  • ex1() throws BaseException
  • ex2() throws CustomException1
  • ex3() throws CustomException2
  • ex4() throws NullPointerException 
  • ex5() throws NumberFormatException

이제 위에 언급한 방법을을 사용하여 이들 예외를 어떻게 처리하는지 둘러보자

방법 1 :  @ControllerAdvice를 사용한 전역 처리Global Exception Handling

클래스에 @ControllerAdvice and @RestController. 를 어노테이션을 추가하면 REST 응답을 리턴하게 될 것이다.

  • @ControllerAdvice는 당신의 스프링 어플리케이션에게 이 클래스가 당신의 어플리케이션의 예외처리를 맡을 거라고 알려주게 된다.
  • @RestController 는 이 클래스를 컨트롤러로 만들어주고 이 클래스가 응답을 렌더할 수 있게 해준다.
  • @ExceptionHandler 어노테이션을 사용하여 예외를 처리할 클래스를 정의한다. ( 기본클래스는 모두 상속되거나 확장된 클래스를 처리할 것이다) 
  • 당신은 @ResponseStatus 어노테이션을 사용하여 예외의 응답 상태를 설정할 수 있다.

HomeController.class

  1. package com.ekiras.controller;  
  2.   
  3. import com.ekiras.exception.BaseException;  
  4. import com.ekiras.exception.CustomException1;  
  5. import com.ekiras.exception.CustomException2;  
  6. import org.springframework.web.bind.annotation.ExceptionHandler;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.bind.annotation.RestController;  
  9.   
  10. /** 
  11.  * @author ekansh 
  12.  * @since 19/2/16 
  13.  */  
  14. @RestController  
  15. @RequestMapping({"","/"})  
  16. public class HomeController {  
  17.   
  18.     @RequestMapping("/ex1")  
  19.     public String ex1(){  
  20.         // 전역 처리자 메소드 handleBaseException에 잡힐 것이다.  
  21.         throw new BaseException("Base Exception");  
  22.     }  
  23.   
  24.     @RequestMapping("/ex2")  
  25.     public String ex2(){  
  26.         //전역 처리자 메소드 handleBaseException에 잡힐 것이다.    
  27.         throw new CustomException1();  
  28.     }  
  29.   
  30.     @RequestMapping("/ex3")  
  31.     public String ex3(){  
  32.         // 전역 처리자 메소드 handleBaseException에 잡힐 것이다.    
  33.         throw new CustomException2();  
  34.     }  
  35.   
  36.     @RequestMapping("/ex4")  
  37.     public String ex4(){  
  38.         //전역 처리자 메소드 handleBaseException에 잡힐 것이다.    
  39.         throw new NullPointerException("null pointer exception");  
  40.     }  
  41.   
  42.     @RequestMapping("/ex5")  
  43.     public String ex5(){  
  44.         // 컨트롤러 예외 처리자 메소드 nfeHandler에 잡힐 것이다.
  45.         throw new NumberFormatException("number format exception");  
  46.     }  
  47.   
  48.     /** 
  49.      * 이 컨트롤러 내에서 발생하는 모든 Number Format 예외를 처리한다     *  
  50.      * */  
  51.     @ExceptionHandler(value = NumberFormatException.class)  
  52.     public String nfeHandler(NumberFormatException e){  
  53.         return e.getMessage();  
  54.     }  
  55.   
  56. }  

GlobalExceptionHandler.class

  1. package com.ekiras.handler.exception;  
  2.   
  3. import com.ekiras.exception.BaseException;  
  4. import org.springframework.http.HttpStatus;  
  5. import org.springframework.web.bind.annotation.ControllerAdvice;  
  6. import org.springframework.web.bind.annotation.ExceptionHandler;  
  7. import org.springframework.web.bind.annotation.ResponseStatus;  
  8. import org.springframework.web.bind.annotation.RestController;  
  9.   
  10. /** 
  11.  * @author ekansh 
  12.  * @since 19/2/16 
  13.  */  
  14. @ControllerAdvice  
  15. @RestController  
  16. public class GlobalExceptionHandler {  
  17.   
  18.     @ResponseStatus(HttpStatus.BAD_REQUEST)  
  19.     @ExceptionHandler(value = BaseException.class)  
  20.     public String handleBaseException(BaseException e){  
  21.         return e.getMessage();  
  22.     }  
  23.   
  24.     @ExceptionHandler(value = Exception.class)  
  25.     public String handleException(Exception e){return e.getMessage();}  
  26.   
  27.   
  28. }  
  • handleBaseException(BaseException e) ::  BaseException, CustomException1 과 CustomException2 클래스들의 예외를 잡는다.
  • handleException(Exception e) ::  Exception클래스의 자식들의 모든 예외를 처리한다.

알림 :: 만일 BaseException 또는 그의 자식 예외가 발생하면 handleException() 메소드가 아닌 handleBaseException()이 이 예외를 잡을 것이다. 

방법 2 : @ExceptionHandler를 사용한 컨트롤러단 예외처리


  1. @ExceptionHandler(value = NumberFormatException.class)  
  2.  public String nfeHandler(NumberFormatException e){  
  3.      return e.getMessage();  
  4.  }  

HomeController.java 에 있는 위의 코드는 이 컨트롤러내에서 발생하는 모든 NumberFormatException를잡을 것이다. 다른 컨트롤러에서 발생하는 NumberFormatException는 처리하지않는다.







반응형

+ Recent posts