没有类级对象的方法中的Spring注入

没有类级对象的方法中的Spring注入,spring,Spring,对于下面的场景,如何通过spring注入 Class A{ public void doSomeThing(){ B builder=new B(); //call other function. } } 这里我不想把B作为类级对象 Class A{ B b;// dont want to bring b here } 我也不想使用SpringContext.getBean(“B”)或autowire 因此Spring必须以如下方式注入B: Class A{ public voi

对于下面的场景,如何通过spring注入

Class A{

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

}
这里我不想把B作为类级对象

Class A{
 B b;// dont want to bring b here
}
我也不想使用SpringContext.getBean(“B”)或autowire

因此Spring必须以如下方式注入B:

Class A{

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

}
A类{
公共无效剂量测定法(){
建筑商=
//调用其他函数。
}
}

因此,在doSomeThing()方法的范围内,使用创建和销毁B。

您可以使用
ApplictionContext
来执行此操作

Class A{
    @Autowire
    private ApplicationContext appContext;

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

如果希望每次调用
appContext.getBean(B.class)
时都有不同的
B
实例,则需要将
B
的bean定义为
原型范围的
bean。

因此,您可能需要以下内容:

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>

您可以通过spring中的lookup方法来实现这一点; 您已经将该类抽象化了,但不要担心spring会为您的抽象类创建一个具体的代理对象

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

<bean id="yourobject" class="com.package.YourClass">
    <lookup-method name="createB" bean="objB" />
</bean>


我认为您需要使用:context.getBean(“B”)它限制了这种情况:试着更具体地描述您的需求。如果您想从Spring中获得一些东西,那么您必须让它在类成员中注入值,或者获取BeanFactory的入口点,无论是静态的还是注入的本身……我没有在ide中尝试过。您仍然需要一个类以主方法启动它od.他确实明确表示不想这样做。虽然我们不知道我为什么尝试使用MethodInvokingFactory,但这需要一个抽象方法。我不能将A更改为抽象方法。因为这将是Web应用程序的一部分。我不想直接使用任何spring上下文对象。我已经指出了您在Common中的建议下面的t不能使类成为抽象的。好的,那么你可以在这里使用替换方法技术,你不必在类中做任何更改。这可以帮助你