Skip to content

Instantly share code, notes, and snippets.

@djkeh
Last active April 30, 2020 02:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djkeh/6194d9123256042be06c6df72a3a3e58 to your computer and use it in GitHub Desktop.
Save djkeh/6194d9123256042be06c6df72a3a3e58 to your computer and use it in GitHub Desktop.
프로토타입 빈 + InjectionPoint를 이용한 최신 스프링 Logger 주입 예제 코드
// 스프링 4.3부터 추가된 InjectionPoint를 이용한 Context-Aware Bean 생성 방법.
@Configuration
public class BeanConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Logger logger(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMethodParameter().getContainingClass());
}
}
@Controller
public class SampleController {
private final Logger logger;
public SampleController(Logger logger) {
this.logger = logger;
}
public void controllerMethod() {
logger.info("LOG!");
}
}
@djkeh
Copy link
Author

djkeh commented Jul 19, 2017

스프링 4.3 이상에서 사용할 수 있는 방법으로 정리하였습니다.

  • SampleController: 생성자 주입 방식을 사용해 logger를 주입합니다. 이 때 스프링 4.3 이후부터는, 단일 생성자를 사용할 경우 @Autowired를 쓰지 않아도 자동으로 해당 필드를 빈 주입 대상으로 보고 빈을 주입합니다. 이전 버젼이라면, 생성자에 @Autowired를 명시하면 됩니다.
  • BeanConfig: Logger 객체를 스프링 빈 컨테이너에 프로토타입 빈으로 등록합니다. InjectionPoint를 이용해 Logger 빈이 불려진 위치의 클래스 정보를 가져옵니다.

@djkeh
Copy link
Author

djkeh commented Jul 19, 2017

이런 방식은 IDE 플러그인 등을 이용해 매번 필드와 생성자 코드를 자동 생성하지 않는 이상, 그래도 반복적으로 타이핑해야 할 부분이 존재한다는 점에서 Lombok 보다는 사용성 면에서 쪼금 더 손이 가겠네요. 대신 로그 객체를 빈으로 등록해 스프링 IoC 컨테이너에게 맡기고 이를 사용 클래스에서 주입 받는 의존 관계가 API에 명확히 드러난다는 점이 좋은 것 같습니다.

@djkeh
Copy link
Author

djkeh commented Apr 19, 2018

이 코드는 spring-projects/spring-boot#8106 에서 논의되었고, 이 코드가 가져오는 이득이 크지 않은 것으로 판단되어 스프링 부트 삽입에 채택되지 않았습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment