spring中如何向一個單例bean中注入非單例bean

北漂程式設計師發表於2021-07-18

看到這個題目相信很多小夥伴都是懵懵的,平時我們的做法大都是下面的操作

@Component
public class People{

@Autowired
private Man man;
}

這裡如果Man是單例的,這種寫法是沒有問題的,但如果Man是原型的,這樣是否會存在問題。

錯誤例項演示

這裡有一個原型(生命週期為prototype)的類

package com.example.myDemo.component;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(value = "prototype")
public class Man  {

    public void eat() {
        System.out.println("I like beef");
    }
}

有一個單例(生命週期為singleton)的類

package com.example.myDemo.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

@Component
public class Woman {
    //使用依賴注入的方式,注入原型的Man
@Autowired
private Man man; public void eat() { System.out.println("man:"+man); System.out.println("I like fruits"); } }

下面看測試方法,

package com.example.myDemo;

import com.example.myDemo.component.MyFactoryBean;
import com.example.myDemo.component.Woman;
import com.example.myDemo.po.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.ApplicationContext;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MyDemoApplication {

    public static void main(String[] args) {
        ApplicationContext ac=SpringApplication.run(MyDemoApplication.class, args);

        Woman woman=(Woman)ac.getBean("woman");
        for(int i=0;i<5;i++){
            woman.eat();
        }


    }

}

看下測試結果,

上面的結果顯示Woman中的man是單例的,因為5次迴圈列印打出的結果是同一個物件,發生了什麼,

Woman是單例的,Man是原型的,我們使用常規的@Autowired註解注入的卻是同一個例項,這裡想下為什麼Man是一個物件,Woman是單例的,意味著在整個spring容器中只有一個例項,在屬性注入的時候肯定也只會注入一次,所以其中Man屬性也只能是一個例項,出現上圖的結果也就不稀奇了。

現在有這樣一個需求要向單例bean中注入原型bean,要怎麼實現這樣的需求

實現ApplicationContextAware介面

都知道ApplicationContextAware介面是spring提供的一個擴充套件點,實現該介面的類可以獲得ApplicationContext

Woamn類改成下面的樣子

 

package com.example.myDemo.component;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Woman implements ApplicationContextAware {

    private Man man;

    private ApplicationContext ac;

    public void eat() {
        this.man = (Man) ac.getBean("man");
        System.out.println("man:" + man);
        System.out.println("I like fruits");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ac = applicationContext;
    }
}

 

Woman實現了ApplicationContextAware介面,注入了ApplicaitonContext物件,然後再eat()方法中通過AppicationContext獲得Man的例項,看測試結果,

可以看到man屬性是多例的也就是符合原型模式的定義。

思考下為什麼採用這種方式可以達到注入原型bean的目的

在eat()方法中使用ApplicationContext的getBean方法獲取Man,eat()方法每執行一次均會呼叫一次getBean方法,getbean方法在執行的時候的時候會判斷Man的生命週期,如果是原型(prototype)的,那麼每呼叫一次就會重新例項化一個Man,所以會出現上述的結果。

 

該方法有一個很大的缺點那就是和spring耦合度太高,不符合降低系統的耦合度的要求。

 

lookup method

spring也考慮了向一個單例bean中注入原型bean的情況,提供了@Lookup註解,在XML配置方式下是<lookup-method>標籤,這裡僅使用註解的方式演示,

Woman類修改如下,

package com.example.myDemo.component;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Woman  {

    private Man man;

    public void eat() {
        this.man = createMan();
        System.out.println("man:" + man);
        System.out.println("I like fruits");
    }

    @Lookup
    public Man createMan(){
        return null;
    }

}

看下測試結果,

上圖顯示man是一個多例的,也就是向單例bean中注入了原型bean,其作用的是@Lookup註解。

通過@Lookup註解便完成了注入原型bean的目的,留個思考問題spring是如何做到的?

lookup method簽名

被@Lookup註解或<lookup-method>配置的方法有如下要求,

  public|protected [abstract] return-type methodName(no-argments)

  • 方法可以是public也可以是protected;
  • 方法可以是抽象的也可以是非抽象的;
  • 方法的返回值是要注入的型別,這裡是prototype型別的類;
  • 方法沒有入參;
  • 方法體可以是空的。具體返回值可以是null或任何型別,對結果沒有影響;

總結

分享了向單例bean中注入原型bean的方式,使用lookup的方式會更簡潔些。

這還可能是道面試題哦,各位小夥伴注意嘍。lookup的原理下次分享,敬請關注

 

推薦閱讀

一次性講清楚spring中bean的生命週期之三:bean是如何例項化的

spring中FactoryBean是什麼bean

 

相關文章