كيف تفعل حقن طريقة البحث في الربيع مع التعليقات التوضيحية؟

StackOverflow https://stackoverflow.com/questions/3891997

سؤال

هل هناك أي طريقة لاستخدام حقن طريقة البحث باستخدام التعليقات التوضيحية؟

بالنظر إلى الفصل التالي:

@Service
public abstract class A {


    protected abstract createB();

}

من أجل الحصول على العمل ، يجب أن أعلن في Spring ApplicationContext.xml ما يلي:

<bean id="b" class="com.xyz.B">
</bean>

<bean id="a" class="com.xyz.A">
    <lookup-method name="createB" bean="b"/>
</bean>

على الرغم من أنني أستخدم <context:component-scan base> لا بد لي من إعلان ذلك أيضا في XML. ليس مقاربة جيدة على ما أعتقد.

كيف تفعل ذلك مع التعليقات التوضيحية؟

هل كانت مفيدة؟

المحلول

من الممكن استخدام javax.inject.Provider. كل شكر يذهب إلى فيل ويب.

public class MySingleton {

  @Autowired
  private Provider<MyPrototype> myPrototype;

  public void operation() {
    MyPrototype instance = myPrototype.get();
    // do something with the instance
  }

}

نصائح أخرى

من الممكن أيضًا مع org.springframework.beans.factory.ObjectFactory إذا كنت ترغب في مواكبة API Spring

public class MySingleton {

  @Autowired
  private ObjectFactory<MyPrototype> myPrototypeFactory;

  public void operation() {
    MyPrototype instance = myPrototypeFactory.getObject();
    // do something with the instance
  }
}

يمكنك قراءة المزيد في توثيق.

يتم تنفيذه فقط مع Spring> = 4.1 انظر تذكرة.

تم تقديمه أخيرًا @ابحث عن حاشية. ملاحظة. هنا نقاش حول كيفية استخدامه.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top