Register bean (with a custom bean name) programmatically

泄露秘密 提交于 2020-01-06 08:01:19

问题


My goal is to register bean (with a custom bean name) programmatically.

@ComponentScan({ "com.test" })
public class AppConfiguration {

    //@Bean("test-bean")
    @Bean
    public Definition definition() {
        return () -> Test.class;
    }
}

@Named
@Scope("prototype")
public class Test extends DefinitionActor<?> {
   ....
}

Here, I use Akka and hence I have to go with @Scope("prototype").

I don't want to hard code the bean name to test-bean for some reason.

Hence, I am using the BeanPostProcessor.

@Component
public class BeanDefinitionRegistryPP implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
    private Environment env;

    @Override
    public void setEnvironment(final Environment environment) {
        this.env = environment;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry) throws BeansException {
}

I am getting AKKA error if I go with this way.

Caused by: akka.actor.ActorInitializationException: You cannot create an instance of [com.test.Test] explicitly using the constructor (new). You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.
    at akka.actor.ActorInitializationException$.apply(Actor.scala:181) ~[akka-actor_2.11-2.4.19.jar:na]

The bean post processor work with non-Akka project. Is there any other way to set the bean name programmatically even I use prototype scope.

来源:https://stackoverflow.com/questions/54356119/register-bean-with-a-custom-bean-name-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!