1. 程式人生 > 其它 >Spring系列之FactoryBean

Spring系列之FactoryBean

 1 package org.springframework.beans.factory;
 2 
 3 import org.springframework.lang.Nullable;
 4 
 5 public interface FactoryBean<T> {
 6     String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
 7 
 8     @Nullable
 9    //返回具體的物件
10     T getObject() throws Exception;
11 
12     @Nullable
13
   //返回物件的具體型別 14 Class<?> getObjectType(); 15 16    //是否是單例,預設為單例 17 default boolean isSingleton() { 18 return true; 19 } 20 }

  建立一個User類,實現此介面

 1 package com.study.factoryBean;
 2 
 3 import org.springframework.beans.factory.FactoryBean;
 4 import org.springframework.stereotype.Component;
5 6 /** 7 * @author Young 8 * @version 1.0 9 * @date 2021/8/5 12:00 10 */ 11 @Component 12 public class UserFactoryBean implements FactoryBean<User> { 13 @Override 14 public User getObject() throws Exception { 15 return new User("張三","13"); 16 } 17 18 @Override 19 public
Class<?> getObjectType() { 20 return User.class; 21 } 22 23 @Override 24 public boolean isSingleton() { 25 return true; 26 } 27 }

 建立啟動類 此demo採用的是註解模式

package com.study.factoryBean;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Young
 * @version 1.0
 * @date 2021/8/5  13:50
 */
public class Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(); //如果在此處()中,加入掃描路徑則不需要呼叫refresh方法
     //指定包掃描路徑 applicationContext.scan(
"com.study.factoryBean"); applicationContext.refresh(); //user類 User user = applicationContext.getBean(User.class); System.out.println(user); //userFactoryBean代理類 com.study.factoryBean.UserFactoryBean$$EnhancerBySpringCGLIB$$ff2ffcf@6b53e23f Object bean = applicationContext.getBean("&userFactoryBean"); System.out.println(bean); //user Object user1 = applicationContext.getBean("userFactoryBean"); System.out.println(user1); } }

總結

  FactoryBean和BeanFactory都是Spring建立bean的一種方式

  FactoryBean沒有BeanFactory建立的過程那麼的繁瑣

  FactoryBean在實現了在getBean時,如果增加了‘&’符號,則get到的為實現FactoryBean介面的代理類,如果不加‘&’則獲取到的為getObject方法的實現