2017-10-17 281 views
0

我是Spring Framework的新手。我遇到了一個情況,我們的bean定義需要引用已經在Java代碼中定義的現有單例。Spring框架Bean是指在Java代碼中定義的單例實例

稍微詳細一點,Foo類的單例(sFoo)在第三方jar文件中定義。而Foo沒有工廠API。 Plus Foo禁止使用與sFoo相同的參數創建實例。因此,由於缺乏Foo類的工廠API,似乎沒有辦法聲明bean(具有單例作用域)。

我需要從其他bean的定義中引用sFoo。

有什麼辦法從bean的定義xml文件中引用sFoo?

由於提前, 弗蘭克

回答

0

配置中的類創建美孚的一個Bean,並指這個Bean只有

@Configuration 
public class ConfigClass { 
    @Bean 
    public Foo foo(){ 
     //This will ensure one object of Foo is created 
     return new Foo(); 
    } 
} 

@Component or @Service or any Spring stereotype annotation 
public OtherClass{ 

    @Autowired 
    Foo foo; //This is the Singleton instance created in ConfigClass 
} 
相關問題