<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                下面來模擬一下Spring的注解開發,關注點就是你<mark>不需要`new`一個對象,依然可以訪問該對象的方法和屬性,那是因為該類已經被反射并`new`好了</mark>。 <br/> 本節示例代碼下載地址:https://gitee.com/flymini/spring/tree/master/mnzj <br/> 步驟如下: [TOC] # 1. 創建一個Web項目 # 2. 代碼封裝過程 **1. 封裝注解** (1)*`org.example.mnzj.anno.Bean`* ```java package org.example.mnzj.anno; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Bean { String value(); } ``` (2)*`org.example.mnzj.anno.Property`* ```java package org.example.mnzj.anno; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Property { String value(); } ``` **2. 將上面定義的兩個注解應用到Java類中** (1)dao層 *`org.example.mnzj.dao.StudentDao`* ```java package org.example.mnzj.dao; public interface StudentDao { Integer queryStudentCounts(); } ``` *`org.example.mnzj.dao.impl.StudentDaoImpl`* ```java package org.example.mnzj.dao.impl; import org.example.mnzj.anno.Bean; import org.example.mnzj.dao.StudentDao; @Bean("studentDao") public class StudentDaoImpl implements StudentDao { public Integer queryStudentCounts() { System.out.println("StudentDaoImpl.queryStudentCounts"); return null; } } ``` (2)service層 *`org.example.mnzj.service.StudentService`* ```java package org.example.mnzj.service; public interface StudentService { Integer queryStudentCounts(); } ``` *`org.example.mnzj.service.impl.StudentServiceImpl`* ```java package org.example.mnzj.service.impl; import org.example.mnzj.anno.Bean; import org.example.mnzj.anno.Property; import org.example.mnzj.dao.StudentDao; import org.example.mnzj.service.StudentService; @Bean("studentService") public class StudentServiceImpl implements StudentService { @Property("studentDao") private StudentDao studentDao; public Integer queryStudentCounts() { System.out.println("StudentServiceImpl.queryStudentCounts"); return studentDao.queryStudentCounts(); } } ``` **3. 對被`@Bean`和`@Property`注解標記的類進行反射** *`org.example.mnzj.common.AnnotationFactory`* ```java package org.example.mnzj.common; import org.example.mnzj.anno.Bean; import org.example.mnzj.anno.Property; import java.io.File; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AnnotationFactory { private static Map<String, Object> map = new HashMap<String, Object>(); public static Object getInstance(String key) { return map.get(key); } static { // 獲取.java文件編譯后的.class文件所在的目錄 String path = AnnotationFactory.class.getClassLoader().getResource("").getPath(); File file = new File(path); initBeans(path); // 初始化被@Bean注解標記的類 initProperties(); // 初始化被@Property注解標記的類 } /** * 找到并初始化被@Bean注解標記的類 * * @param path String, .class文件所在的目錄 */ private static void initBeans(String path) { File file = new File(path); File[] subFiles = file.listFiles(); for (File subFile : subFiles) { if (subFile.isDirectory()) { initBeans(subFile.getPath()); } else { // 實例化被@Bean注解的類 initBean(subFile.getPath()); } } } /** * 實例化被@Bean注解標記的類 * * @param path String, .class文件所在的目錄 */ private static void initBean(String path) { if (!path.endsWith(".class")) { return; } // 獲取被@Bean注解標記的類的完全限定名 int begin = AnnotationFactory.class.getClassLoader().getResource("").getPath().length(); int end = path.lastIndexOf("."); String className = path.substring(begin - 1, end); className = className.replace("\\", "."); try { Class cls = Class.forName(className); // 加載類 // 判斷該類是否被@Bean注解標記 if (cls.isAnnotationPresent(Bean.class)) { Object instance = cls.newInstance(); // 實例化該類 Bean annotation = (Bean) cls.getDeclaredAnnotation(Bean.class); map.put(annotation.value(), instance); } } catch (Exception e) { e.printStackTrace(); } } /** * 實例化被@Property注解標記的屬性 */ private static void initProperties() { for (Object instance : map.values()) { Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Property.class)) { Property annotation = field.getAnnotation(Property.class); String key = annotation.value(); Object obj = map.get(key); field.setAccessible(true); try { field.set(instance, obj); } catch (Exception e) { e.printStackTrace(); } } } } } } ``` **4. 封裝controller層** (1)*`org.example.mnzj.common.BaseServlet`* ```java package org.example.mnzj.common; import org.example.mnzj.anno.Property; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Field; import java.lang.reflect.Method; public class BaseServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) { String methodName = request.getParameter("method"); try { Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.setAccessible(true); String url = (String) method.invoke(this, request, response); if (url == null) { return; } if (url.startsWith("redirect:")) { int index = url.indexOf(":"); url = url.substring(index + 1); response.sendRedirect(url + ".jsp"); } else { request.getRequestDispatcher(url + ".jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } /** * 對繼承該類的子類的成員屬性進行賦值 * * @throws ServletException */ @Override public void init() throws ServletException { Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Property.class)) { Property annotation = field.getAnnotation(Property.class); String key = annotation.value(); Object obj = AnnotationFactory.getInstance(key); try { field.setAccessible(true); field.set(this, obj); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } ``` (2)*`org.example.mnzj.controller.StudentController`* ```java package org.example.mnzj.controller; import org.example.mnzj.anno.Property; import org.example.mnzj.common.BaseServlet; import org.example.mnzj.service.StudentService; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/student") public class StudentController extends BaseServlet { @Property("studentService") private StudentService studentService; private String welcome(HttpServletRequest request, HttpServletResponse response) { System.out.println("IndexController.doGet方法執行-----start"); studentService.queryStudentCounts(); System.out.println("IndexController.doGet方法執行-----end"); return null; } } ``` **5. 測試** 啟動項目后訪問 http://localhost:8080/mnzj_war_exploded/student?method=welcome ,控制臺打印的結果如下: ``` IndexController.doGet方法執行-----start StudentServiceImpl.queryStudentCounts StudentDaoImpl.queryStudentCounts IndexController.doGet方法執行-----end ``` 上面寫了那么多,其目的就想實現一個功能:我不`new`一個對象,但是我依然能夠訪問它的方法。 <br/> 在上面的代碼中,`StudentServiceImpl ` 中調用了`StudentDao.queryStudentCounts`方法;在 `StudentController` 中調用了`StudentService.queryStudentCounts`方法。但是請注意我并沒有實例化`StudentDaoImpl`和`StudentServiceImpl`類,因為這兩個類被`@Bean`注解標記,作為屬性時被`@Property`注解標記,然后在 `AnnotationFactory` 反射了被這兩個注解標記的類并實例化了這個兩個類,并在 `BaseServlet` 的`init`方法中對繼承`BaseServlet`的子類的屬性進行賦值,所以當我們調用方法時,對象已在`AnnotationFactory`幫我們自動實例化了。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看