2017-10-17 282 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 
} 
相关问题