![](/img/trans.png)
[英]Apache Camel - Spring DSL - Pass String argument to bean method
[英]Trying pass String argument while creating bean Spring boot
我有一个如下定义的bean..上下文是自动装配的..
@Autowired
private ApplicationContext context;
...
RabbitQueue queue = (RabbitQueue) context.getBean("rabbitQueue");
QueueName queueNameTest = (QueueName) context.getBean("QueueName", "audittesting");
此 queueNameTest 将作为参数传递给另一个 bean 创建。
Queue q1= queue.createQueue(queueNameTest);
这个 createQueue bean 定义就像..
@Bean
public Queue createQueue(QueueName queueName) {
String strQueueName = queueName.getQueueName();
logger.info("Created rabbitmq queue {}", strQueueName);
return QueueBuilder
.durable(strQueueName)
.withArguments(deadLetterArgs(AuditRabbitMQConstants.DL_ROUTING_KEY))
.build();
}
现在在 QueueName class 我有..
@Component
public class QueueName {
private String arg;
public QueueName(String arg) {
this.arg = arg;
}
public String getQueueName()
{
return arg;
}
}
当我试图跑步时..我得到
n***************************nAPPLICATION FAILED TO STARTn***************************nDescription:nParameter 0 of constructor in com.rabbitmq.QueueName required a bean of type 'java.lang.String' that could not be found.nAction:nConsider defining a bean of type 'java.lang.String' in your configuration.n"}
基本上我需要在运行时动态地将参数传递给 createQueue() .. 我该如何实现呢?
您需要以编程方式创建一个 bean
尝试以下
ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)context;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
Queue myQueue = createQueue("myString");
beanRegistry.registerSingleton("queue", myqueue);
//remove @bean from here it will not be created automatically
//keep the method to create bean programmaticaly
public Queue createQueue(QueueName queueName) {
String strQueueName = queueName.getQueueName();
logger.info("Created rabbitmq queue {}", strQueueName);
return QueueBuilder.durable(strQueueName)
.withArguments(deadLetterArgs(AuditRabbitMQConstants.DL_ROUTING_KEY))
.build();
}
//Remove @Component from here it will not be created automatically
public class QueueName {
如果你有某个地方
@Autowired
Queue queue
然后做
@Autowired
@Lazy
Queue queue
因为它将被延迟初始化。
编辑:根据这里询问的评论是如何动态注册原型bean
如果您使用的是 Spring 5 或更高版本,您可以使用GenericApplicationContext
public yourClass {
@Autowired
private GenericApplicationContext context;
public Queue registerQueue(QueueName queueName) {
String strQueueName = queueName.getQueueName();
logger.info("Created rabbitmq queue {}", strQueueName);
context.registerBean(queueName, Queue.class, ()->
QueueBuilder.durable(strQueueName)
.withArguments(deadLetterArgs(AuditRabbitMQConstants.DL_ROUTING_KEY))
.build() );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.