6
votes

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

1

1 Answers

0
votes

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.