Spring   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java – 自定义Spring Bean参数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用在activator上发布的Spring Akka示例来创建Spring托管bean演员.这是我目前正在使用的代码,包括一个演示类:

@Component
class Test extends UntypedActor {

    @Autowired
    protected ObjectMapper objectMapper;

    protected final Account account;
    protected final Order order;

    public Test(Account account,Order order) {
        this.account = account;
        this.order = order;
    }

    @Override
    public void onReceive(Object messagE) throws Exception {
        if (message instanceof someCommand) {
            // Do something using the order and the account;
        } else if (message instanceof FooCommand) {
            // More stuff
        }
    }
}

@Component
public class SpringExtension extends AbstractExtensionId@L_607_4@ sy@L_607_4@) {
        return applicationContext.getBean(SpringExtensionImpl.class);
    }

    @Override
    public ExtensionId

现在我的问题是,如何用自定义构造函数参数实例化一个actor.我曾虑使用工厂或setter方法,但我不认为这是一个选项,因为我相信底层的Actor类是不可访问的.关于此事的任何意见都非常感谢.如果现在有问题,请发表评论.

Ps.如果您认为我的代码中存在错误或有更好的解决方法,请告诉我!我对Spring和Akka的经验很少,所以任何建议都表示赞赏.

最佳答案
您可以将其他参数作为varargs(Object …)传递给SpringExtensionImpl和SpringActorProducer.所以你的代码看起来像这样

@Component
public class SpringExtensionImpl implements Extension {

   @Autowired
   private ApplicationContext applicationContext;

   public Props props(String actorBeAnname,Object... args) {
       return (args != null && args.length > 0) ?
            Props.create(SpringActorProducer.class,actorBeAnname,args) :
            Props.create(SpringActorProducer.class,actorBeanName);
    }
}

public class SpringActorProducer implements IndirectActorProducer {

    private final ApplicationContext applicationContext;
    private final String actorBeAnname;
    private final Object[] args;

    public SpringActorProducer(ApplicationContext applicationContext,String actorBeanName) {
        this.applicationContext = applicationContext;
        this.actorBeAnname = actorBeAnname;
        this.args = null;
    }

    public SpringActorProducer(ApplicationContext applicationContext,String actorBeAnname,Object... args) {
        this.applicationContext = applicationContext;
        this.actorBeAnname = actorBeAnname;
        this.args = args;
    }

    @Override
    public Actor produce() {
        return args == null ? 
              (Actor) applicationContext.getBean(actorBeanName):
              (Actor) applicationContext.getBean(actorBeAnname,args);
    }

    @Override
    public Class

然后,您可以像这样创建Test actor:

SpringExtensionImpl springExtensionImpl;
actorSy@L_607_4@.actorOf(springExtensionImpl.create(Test.class,account,order));

大佬总结

以上是大佬教程为你收集整理的java – 自定义Spring Bean参数全部内容,希望文章能够帮你解决java – 自定义Spring Bean参数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。