spring面試
阿新 • • 發佈:2021-01-01
spring流程圖
https://www.processon.com/view/link/5feef2e0e401fd661a0b06fc
手寫AutoWired註解,瞭解反射建立物件
https://github.com/Q2021/spring/tree/master/src
package org.example.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD)public @interface AutoWired { }
package org.example.controller; import org.example.annotation.AutoWired; import org.example.service.UserService; public class UserController { @AutoWired private UserService userService; public UserService getUserService() { return userService; } }
@Test public void test02() { UserController userController = new UserController(); Class<? extends UserController> clazz = userController.getClass(); //獲取所有屬性值 Stream.of(clazz.getDeclaredFields()).forEach(field -> { AutoWired annotation = field.getAnnotation(AutoWired.class); if (annotation != null) { field.setAccessible(true); //獲取屬性型別 Class<?> type = field.getType(); try { Object o = type.newInstance(); field.set(userController, o); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); System.out.println(userController.getUserService()); }