1

我如何在 Spring 中声明这些 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;
    }
}
4

2 回答 2

0

配置文件

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

爪哇

@Component
public class A {
  @Autowired
  public void setB(B b) {
    this.b = b;
  }
}
于 2013-09-25T21:37:30.517 回答
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
于 2013-09-26T02:36:01.200 回答