spring 블로그에 게시되어 있는 spring *Utils 클래스들에 대한 활용 팁이다.
블로그에 youtube 영상과 함께 자세히 설명하고 있다. Spring Tips: The Spring Framework *Utils Classes
크게 보면 아래 Utils들의 설명을 하고 있다.
BeanUtils : JavaBean의 util 클래스로 bean의 초기화, property의 검사, property 복사 등의 함수 포함.
ClassUtils : Class의 name, method 확인 및 reflection util을 포함. ReflectionUtils와 기능의 차이 비교가 필요하다.
SystemPropertyUtils : system property의 값을 손쉽게 가지고 올 수 있는 util
FileCopyUtils : file copy와 관련된 util. stream copy 기능도 가지고 있다.
AopUtils : spring aop를 지원하는 code에 대한 util
ReflectionUtils : reflection을 위한 util.
Utils에 Reflection 요소가 많아서 framework 확장을 위한 코드를 작성할 때 유용할 것 같다.
그리고 SystemPropertyUtils을 사용해서 property를 바로 불러올 수 있는데, @Value를 사용하던 것에서 간단한 부분은 SystemPropertyUtils로 변경할 수 있을 듯 하다.
아래는 youtube에 설명한 코드의 전체이다.
@Slf4j
@EnableAspectJAutoProxy
@SpringBootApplication
public class DemoApplication {
@Aspect
@Component
public static class SimpleBeforeAspect {
@Before("execution(* begin(..))")
public void before(JoinPoint joinPoint) {
log.info("-----------");
log.info("before()");
log.info("signature: " + joinPoint.getSignature());
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DemoClass {
@PostConstruct
public void begin() {
log.info("begin()");
}
private List<Map<String, Object>> list = new ArrayList<>();
}
@Bean
DemoClass demoClass() {
return new DemoClass();
}
@Bean
CommandLineRunner demo(DemoClass demo) {
return args -> {
Assert.notNull(demo.getList(), "the list can't be null");
beansUtils(demo);
classUtils();
systemPropertyUtils();
fileCopyUtils();
web();
aop(demo);
reflection();
};
}
private void reflection() {
ReflectionUtils.doWithFields(DemoClass.class, field -> log.info("field = " + field.toString()));
ReflectionUtils.doWithMethods(DemoClass.class, method -> log.info("method = " + method.toString()));
Field list = ReflectionUtils.findField(DemoClass.class, "list");
log.info(list.toString());
ResolvableType rt = ResolvableType.forField(list);
log.info(rt.toString());
}
private void aop(DemoClass demo) {
Class<?> targetClass = AopUtils.getTargetClass(demo);
log.info("Class<?> is " + targetClass);
log.info("is AOP proxy? " + AopUtils.isAopProxy(demo));
log.info("is CGlib proxy? " + AopUtils.isCglibProxy(demo));
}
private void web() {
RestTemplate rt = new RestTemplate();
rt.getForEntity("http://localhost:8080/hi", Void.class);
}
@RestController
public static class SimpleRestController {
@GetMapping("/hi")
void hi (HttpServletRequest request) {
long age = ServletRequestUtils.getIntParameter(request, "age", 18);
log.info("age is " + age);
File tempDir = WebUtils.getTempDir(request.getServletContext());
log.info("temporary directory for Apache Tomcat is " + tempDir.getAbsolutePath());
ApplicationContext webApplicationContext = RequestContextUtils.findWebApplicationContext(request);
Environment bean = webApplicationContext.getBean(Environment.class);
log.info("webApplicationContext resolved property = " + bean.getProperty("user.home"));
}
}
private void fileCopyUtils() {
File file = new File(SystemPropertyUtils.resolvePlaceholders("${user.home}"), "/Desktop/content.txt");
try (Reader r = new FileReader(file)) {
log.info("contents of file " + FileCopyUtils.copyToString(r));
} catch (Exception e) {
e.printStackTrace();
}
}
private void systemPropertyUtils() {
String resolvedText = SystemPropertyUtils.resolvePlaceholders("my home directory is ${user.home}");
log.info("resolved text:" + resolvedText);
}
private void classUtils() {
Constructor<DemoClass> demoClassConstructor = ClassUtils.getConstructorIfAvailable(DemoClass.class);
log.info("demoClassConstructor: " + demoClassConstructor);
try {
DemoClass demoClass = demoClassConstructor.newInstance();
log.info("newInstance'd demoClass: " + demoClass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void beansUtils(DemoClass demo) {
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(demo.getClass());
for (PropertyDescriptor pd : descriptors) {
log.info("pd: " + pd.getName());
// log.info("pd.readMethod: " + pd.getReadMethod().getName());
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}반응형
'Framework > spring' 카테고리의 다른 글
| [spring boot] spring boot configuration 이해 (0) | 2017.08.30 |
|---|---|
| [spring] lifecycle mechanisms (0) | 2017.08.29 |
| [spring] cache (0) | 2017.08.29 |
| [spring security] Controller에서 Principal 가져오기 (0) | 2016.03.24 |