如何使用注解进行 Spring 查找方法注入? [英] How to do Spring Lookup Method Injection with Annotations?

查看:22
本文介绍了如何使用注解进行 Spring 查找方法注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用注解来使用查找方法注入?

Is there any way to use Lookup Method Injection using annotations?

给定以下类:

@Service
public abstract class A {


    protected abstract createB();

}

为了让它工作,我必须在 spring applicationContext.xml 中声明以下内容:

In order to get it to work I have to declare in spring applicationContext.xml the following:

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

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

即使我使用 我也必须在 XML 中声明它.我认为这不是一个好方法.

Even though I am using <context:component-scan base> I have to declare it also in the XML. Not a good approach I think.

如何使用注解来实现?

推荐答案

可以使用 javax.inject.Provider.感谢 菲尔·韦伯.

public class MySingleton {

  @Autowired
  private Provider<MyPrototype> myPrototype;

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

}

这篇关于如何使用注解进行 Spring 查找方法注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆