Souvik
Souvik

Reputation: 1269

Spring Dependency Injection with anotaation in constructor with parameter

I have below Spring class which I want to load with Spring DI. With default-constructor it's working as expected but can anyone tell me the annotation details and syntax with constructor with string arguments. This string arguments are run time.

I have tried with XML configuration "constrctor args" and working as expected.

    public someclass(String hostName, int port, String user, String password) {
        this.user = user;
        this.password = password;
    }

Upvotes: 1

Views: 1490

Answers (1)

nsylmz
nsylmz

Reputation: 277

I assume your fields(hastName, port, user and password) are coming from properties file like for a server configuration.

@Component
public class SomeClass {

    @Autowired
    public someclass(@Value("${server.hostName}") String hostName, @Value("${server.port}") int port, @Value("${server.user}") String user, @Value("${server.passowrd}") String password ) {
        this.user = user;
        this.password = password;
    }
}

If your params aren't static values, you would use programmatic way. You need to autowire application context before you create instance of your bean.

@Autowired
private ApplicationContext ctx;

Then, create your bean instance and register it to application context,

BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) ctx.getFactory());  

GenericBeanDefinition beanDefinition = new GenericBeanDefinition();  
beanDefinition.setBeanClass(SomeClass.class);  
beanDefinition.setLazyInit(false);  
beanDefinition.setAbstract(false);  
beanDefinition.setAutowireCandidate(true);  
beanDefinition.setScope("singleton"); // you should deal your scope.
ConstructorArgumentValues constructor = beanDefinition.getConstructorArgumentValues();
constructor.addIndexedArgumentValue(0, hostName);
constructor.addIndexedArgumentValue(1, port);
constructor.addIndexedArgumentValue(3, user);
constructor.addIndexedArgumentValue(4, password);

String beanName = "someclass"; // give a name to your bean

BeanComponentDefinition definition = new BeanComponentDefinition(beanDefinition, beanName);
BeanDefinitionReaderUtils.registerBeanDefinition(definition, registry);

Be careful while dealing your bean scope. You may use request or session scope according your structure.

At last, you can autowire SomeClass in other classes;

@Autowired
public SomeClass someClass;

Upvotes: 2

Related Questions