Nicolas Labrot
Nicolas Labrot

Reputation: 4116

How to create dynamic beans which have only a constructor with args

I have a bean with final field.

public class Foo {
   Service service;
   final String bar;
   public Foo(String bar){};
}

service is not final and has a setter. bar is final and can have many values. I cannot remove the final keyword. I try to create a spring factory that allows to create Foo's instances with injected service and dynamic bar value. factory.create(bar). Foo beans are instanciated at runtime because bar value is not known and unbounded

I have try:

Any idea ?

Thanks!

Upvotes: 0

Views: 925

Answers (2)

lunr
lunr

Reputation: 5279

Take a look at ApplicationContext.getBean(String name, Object... args) method. You can pass arguments to bean creation with args parameter.

Upvotes: 4

cowls
cowls

Reputation: 24354

You can use constructor injection in the Application Context XML as one way to do this:

<bean name="foo" class="com.example.Foo">

   <constructor-arg index="0">Bar</constructor-arg>

</bean>

EDIT: Missed that, check out this question: How to use @Autowired in spring

The second answer (not by me)

It looks like you might be able to use @Configurable annotation here.

Upvotes: 0

Related Questions