Răsfoiți Sursa

2024年4月3日 10点19分

Starlight-0208 7 luni în urmă
părinte
comite
3e229b69ca

+ 1 - 0
src/main/java/org/starter/learning/AppTest.java

@@ -22,5 +22,6 @@ public class AppTest {
 //        List<Book> bookList1 = bookService.listBook();
         BookService bookService1 = (BookService) ctx.getBean("bookService");
         bookService1.listBook();
+        System.out.println(BookService.class);
     }
 }

+ 21 - 0
src/main/java/org/starter/learning/factory/BookDaoFactoryBean.java

@@ -0,0 +1,21 @@
+package org.starter.learning.factory;
+
+import org.springframework.beans.factory.FactoryBean;
+import org.starter.learning.dao.BookDao;
+import org.starter.learning.dao.impl.BookDaoImpl;
+
+// FactoryBean的泛型,你的工厂需要生产什么类型的对象就填什么类型
+public class BookDaoFactoryBean implements FactoryBean<BookDao> {
+
+    // 代替原始工厂中创建实例对象的方法,这个就是统一的对象创建方法名
+    @Override
+    public BookDao getObject() throws Exception {
+        return new BookDaoImpl();
+    }
+
+    // 这个方法返回的是需要创建的对象的类型,直接将对象的class字节码返回即可
+    @Override
+    public Class<?> getObjectType() {
+        return BookDao.class;
+    }
+}

+ 5 - 4
src/main/resources/applicationContext.xml

@@ -5,13 +5,14 @@
     <!--配置Bean-->
 <!--    <bean id="bookDao" class="org.starter.learning.dao.impl.BookDaoImpl" />-->
     <!--配置方式2:工厂模式-->
-    <bean id="bookDao" class="org.starter.learning.factory.BookDaoFactory" factory-method="getBookDao" />
+<!--    <bean id="bookDao" class="org.starter.learning.factory.BookDaoFactory" factory-method="getBookDao" />-->
     <!-- 配置方式3:实例工厂模式 -->
     <!-- 将实例工厂本身实例化 -->
-    <bean id="bookServiceFactory" class="org.starter.learning.factory.BookServiceFactory" />
+<!--    <bean id="bookServiceFactory" class="org.starter.learning.factory.BookServiceFactory" />-->
     <!-- 通过工厂本身来创建对象 -->
-    <bean id="book" factory-bean="bookServiceFactory" factory-method="getBookService" />
-
+<!--    <bean id="book" factory-bean="bookServiceFactory" factory-method="getBookService" />-->
+    <!-- 配置方式4:FactoryBean方式实例化 -->
+    <bean id="bookDao" class="org.starter.learning.factory.BookDaoFactoryBean" />
     <bean id="bookService" class="org.starter.learning.service.impl.BookServiceImpl">
         <!--配置Service和Dao之间的关系-->
         <!--property标签表示配置当前bean的属性-->