2017-10-20 66 views
0

我在類和接口之下創建了,但原型bean構造函數沒有被調用。我正在使用@Lookup來創建原型範圍的bean。無法使用@Lookup註解在單例bean中的原型範圍中自動裝入bean

public interface IProtoTypeBean {} 

@Component 
@Scope(value = "prototype") 
public class ProtoTypeBean implements IProtoTypeBean { 

    public ProtoTypeBean() { 
     super(); 
     System.out.println("ProtoTypeBean"); 
    } 
} 

@Component 
public class SingleTonBean { 

    IProtoTypeBean protoTypeBean = getProtoTypeBean(); 

    @Lookup 
    public ProtoTypeBean getProtoTypeBean(){ 
     return null; 
    } 

    public static void main(String[] args) { 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class); 
     SingleTonBean s1 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p1 = s1.protoTypeBean; 
     SingleTonBean s2 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p2 = s2.protoTypeBean; 
     System.out.println("singelton beans " + (s1 == s2)); 

     // if ProtoTypeBean constructor getting called 2 times means diff objects are getting created 
    } 

} 

回答

0

更改您的代碼下面的步驟

@Component("protoBean") 
@Scope(value = "prototype") public class ProtoTypeBean implements IProtoTypeBean { 

而且

@Lookup(value="protoBean") 
public abstract ProtoTypeBean getProtoTypeBean(); 
+0

感謝,但沒有奏效,我應該在哪裏定義抽象getProtoTypeBean方法。 –

+0

更新getProtoTypeBean()並將其抽象爲 – Mudassar

+0

我應該把它放在另一個抽象類 –

0

我建議使用原型提供商

添加行家依賴

<dependency> 
     <groupId>javax.inject</groupId> 
     <artifactId>javax.inject</artifactId> 
     <version>1</version> 
    </dependency> 

然後提兩個班由Spring

ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class); 

進行管理,這裏是供應商使用

@Component 
    public class SingleTonBean { 

    @Autowired 
    private Provider<IProtoTypeBean> protoTypeBeanProvider; 

    public IProtoTypeBean getProtoTypeBean() { 
     return protoTypeBeanProvider.get(); 
    } 

    public static void main(String[] args) { 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class); 
     SingleTonBean s1 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p1 = s1.getProtoTypeBean(); 
     SingleTonBean s2 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p2 = s2.getProtoTypeBean(); 
     System.out.println("singleton beans " + (s1 == s2)); 
     System.out.println("prototype beans " + (p1 == p2)); 
    } 
} 
+0

請讓我知道是否有任何使用提供程序的優勢,而不是查找註釋 –

+0

@VikrantChaudhary,恕我直言,供應商是使用更清潔技術。有一個由Spring自動裝配的工廠,它有get()方法創建新的prototype bean。相反,查找方法返回null,儘管它將被Spring重寫。 –

+0

謝謝安德烈.. –

相關問題