當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【Spring注解系列06】FactoryBean注入对象用法
生活随笔
收集整理的這篇文章主要介紹了
【Spring注解系列06】FactoryBean注入对象用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用Spring提供的 FactoryBean(工廠Bean);
1)、默認獲取到的是工廠bean調用getObject創建的對象
2)、要獲取工廠Bean本身,我們需要給id前面加一個&
? ? ? ? ?&colorFactoryBean
實例類與配置類
測試
public class FactoryBeanTest {public static void main(String[] args) {ApplicationContext applicationContext = new AnnotationConfigApplicationContext(FactoryBeanConfig.class);//bean1看到的好像是ColorFactoryBean,實際上是Color的beanObject bean1 = applicationContext.getBean("colorFactoryBean");Object bean2 = applicationContext.getBean("colorFactoryBean");System.out.println(bean1);System.out.println(bean1==bean2);//設置為isSingleton返回值為true時,為單例//獲取ColorFactoryBean本身ColorFactoryBean colorFactoryBean = (ColorFactoryBean) applicationContext.getBean("&colorFactoryBean");System.out.println(colorFactoryBean);} }結果: ImportBeanByFactoryBean...............getObject //調用factoryBean的getObject方法 com.java.model.Color@2df32bf7 //注入對象實際為Color,而不是ColorFactoryBean true //單例相同 com.java.model.ColorFactoryBean@530612ba //獲取本身個人覺得FactoryBean沒什么作用,既然要單獨注入Factorybean的實現類,為什么不直接注入要注入的對象呢?
Spring底層好像有大量應用。查看了一下FactoryBean的實現類,這個大部分都是用于代理對象。 用法值得再深入了解一下。
factoryBean接口上的注釋:
* <p>This interface is heavily used within the framework itself, for example for * the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} or the * {@link org.springframework.jndi.JndiObjectFactoryBean}. It can be used for * custom components as well; however, this is only common for infrastructure code. *意思:該接口主要用于Spring框架內部,比如AOP或者JndiObjectFactoryBean等。它也能用于自定義組件, *但是只適用于有共同基礎架構代碼的組件。 * * <p><b>{@code FactoryBean} is a programmatic contract. Implementations are not * supposed to rely on annotation-driven injection or other reflective facilities.</b> * {@link #getObjectType()} {@link #getObject()} invocations may arrive early in * the bootstrap process, even ahead of any post-processor setup. If you need access * other beans, implement {@link BeanFactoryAware} and obtain them programmatically. *意思:factoryBean是一個工程契約。實現它不應該依賴于注解驅動注入或者其他反射協助。 * getObjectType和getObject方法調用可能在引導程序處理之前,甚至在后置處理器賦值之前。 * 如果操作時需要訪問其他bean,則需要實現BeanFactoryAware接口,來獲得這些工程對象。 * * <p>Finally, FactoryBean objects participate in the containing BeanFactory's * synchronization of bean creation. There is usually no need for internal * synchronization other than for purposes of lazy initialization within the * FactoryBean itself (or the like). *意思:最后,FactoryBean對象參與包含BeanFactory的bean創建同步。除了在FactoryBean本身 * (或類似的)中進行延遲初始化之外,通常不需要內部同步。?
總結
以上是生活随笔為你收集整理的【Spring注解系列06】FactoryBean注入对象用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Spring注解系列05】@Impor
- 下一篇: gradle idea java ssm