#22 mvc: reflection - annotation scan

This commit is contained in:
haerong22
2022-09-21 23:50:34 +09:00
parent 67c8588ada
commit 54edba1b02
13 changed files with 449 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
package org.example;
public class Main {
}

View File

@@ -0,0 +1,11 @@
package org.example.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}

View File

@@ -0,0 +1,15 @@
package org.example.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value() default "";
RequestMethod[] method() default {};
}

View File

@@ -0,0 +1,5 @@
package org.example.annotation;
public enum RequestMethod {
GET, POST, PUT, PATCH, DELETE
}

View File

@@ -0,0 +1,17 @@
package org.example.controller;
import org.example.annotation.Controller;
import org.example.annotation.RequestMapping;
import org.example.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class HealthCheckController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String health(HttpServletRequest request, HttpServletResponse response) {
return "ok";
}
}

View File

@@ -0,0 +1,17 @@
package org.example.controller;
import org.example.annotation.Controller;
import org.example.annotation.RequestMapping;
import org.example.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(HttpServletRequest request, HttpServletResponse response) {
return "home";
}
}

View File

@@ -0,0 +1,25 @@
package org.example;
import org.example.annotation.Controller;
import org.junit.jupiter.api.Test;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
public class ReflectionTest {
private static final Logger logger = LoggerFactory.getLogger(ReflectionTest.class);
@Test
void controllerScan() {
Reflections reflections = new Reflections("org.example");
Set<Class<?>> beans = new HashSet<>();
beans.addAll(reflections.getTypesAnnotatedWith(Controller.class));
logger.debug("beans: [{}]", beans);
}
}