CDI: manual creating beans with constructor arguments
Asked Answered
G

1

6

I have a class which I want to be a bean

public class SomeBean{
   public SomeBean(){
     //default constructor
   }
   public SomeBean(String someStr){
    //constructor with arguments.
   }
}

In order to create manually CDI bean I do the following

Bean<?> bean = (Bean<?>) beanManager.resolve(beanManager.getBeans(SomeBean.class));
SomeBean someBean =(SomeBean) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));

However the above method will create SomeBean instance wth default constructor. How can I create bean and pass String argument to construcot? P.S. CDI - WELD

Guaiacol answered 8/6, 2015 at 8:38 Comment(0)
T
0

The standard way to define beans with given constructor arguments is via a producer method, e.g.

@Produces @ApplicationScoped @MyQualifier
public SomeBean myBean() {
    return new SomeBean("foo");
}

Application code should not normally have to use the BeanManager, unless you want to create a CDI extension.

Tax answered 8/6, 2015 at 13:55 Comment(1)
I know about produces and understand you. But I need for my situation manual creating.Guaiacol

© 2022 - 2024 — McMap. All rights reserved.