3

在以下情况下如何通过 spring 注入。

Class A{

public void doSomeThing(){
 B builder=new B();
 //call other function.
}

}

在这里,我不想将 B 作为类级别的对象。

Class A{
 B b;// dont want to bring b here
}

我也不想使用 Spring context.getBean("B) 或 autowire;

所以 Spring 必须以以下方式注入 B:

Class A{

public void doSomeThing(){
 B builder=<injected by Spring>
 //call other function.
}

}

所以 B 在 doSomeThing() 方法的范围内被创建和销毁。

4

3 回答 3

2

你可以用它ApplictionContext来做到这一点

Class A{
    @Autowire
    private ApplicationContext appContext;

    public void doSomeThing(){
        B builder=appContext.getBean(B.class);
    }
}

如果您希望B每次调用时都有不同的实例,appContext.getBean(B.class)那么您需要将 bean 定义Bprototype scopedbean。

于 2013-02-27T15:37:33.037 回答
0

所以你可能想要这样的东西:

class A {
    B b;

    public void doSomething() {
        b.something();
    }

    public B getB() {
        return b;
    }

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

class B {
    public void something() {
        System.out.println("something");
    }
}

然后您的 XML 配置将是:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
  <bean id="a"  class="A">
    <property name="b" ref="b"/>
  </bean>

  <bean id="b" class="B"/>

</beans>
于 2013-02-27T15:41:35.003 回答
0

你可以在春天通过查找方法来做到这一点。创建一个抽象方法 createB(); 并且您已经使该类也抽象了,但不要担心 spring 会为您的抽象类创建一个具体的代理对象。

<bean id="objB" class="com.package.Prototype" scope="prototype" />

<bean id="yourobject" class="com.package.YourClass">
    <lookup-method name="createB" bean="objB" />
</bean>
于 2015-05-18T09:42:09.137 回答