2013-09-25 35 views
1

如何在春天宣佈這些bean宣言中的一類豆類有從工廠方法返回另一個類

class A 
{ 
    private B b; 

    public void setB(B b) 
    { 
     this.b = b; 
    // I want to inject this through Spring but the value returned from factory method of C 
    } 

} 

class C 
{ 
    private static B b; 

    public static getB() 
    { 
     return b;//return one instance of B; 
    } 
} 

回答

0

Config.java

@Configuration 
public class Config { 
    @Bean 
    B getB() { 
    return C.staticFactoryMethod(); 
    } 
} 

一個對象的引用的.java

@Component 
public class A { 
    @Autowired 
    public void setB(B b) { 
    this.b = b; 
    } 
} 
+0

這是setter注入。你也可以在A中添加一個構造函數來獲取一個B實例並將其標記爲'Autowired',或者你可以在A中包含一個實例變量B,並將變量聲明標記爲'Autowired',無論哪種浮動。 – digitaljoel

0

爲了完整起見,我張貼這樣做的XML配置方式。

的SSCCE

package Test; 

import org.springframework.context.support.ClassPathXmlApplicationContext; 

public class Main extends HttpServlet { 
    static class A 
    { 
     private B b; 

     public void setB(B b) 
     { 
      this.b = b; 
     } 

     public B getB() { 
      return b; 
     } 
    } 

    static class B {} 

    static class C 
    { 
     private static B b = new B(); 

     public static B getB() 
     { 
      return b; 
     } 
    } 

    public static void main(String[] args) { 
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); 
     A a = (A) context.getBean(A.class); 
     System.out.println(a.getB() == C.getB()); 
    } 
} 

語境

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean class="Test.Main.A"> 
     <property name="B"> 
      <bean class="Test.Main.C" factory-method="getB"></bean> 
     </property> 
    </bean> 
</beans> 

打印

true 
相關問題