1

I want to create a object using few properties, how can I achieve that using Spring @Autowired ? E.g.-

public class Person{
private String fname;
private String lname;
public Person(String fname, String lname){
    this.fname = fname;
    this.lname = lname;
}

}

How can I create a object using @Autowired of Person class by passing these properties at runtime.

Atul

1 Answer 1

3

Do you really want to autowire the variables? Or do you want to set them explictly when getting the bean?

In the later case, you can simply call ApplicationContext.getBean(Class<T> clz, Object ... arguments), in your case...

Person person = context.getBean(Person.class, "Henry", "Miller");

Obviously that doesn't have anything to do with @Autowired. Or do you want to autowire some strings into it? In that case you normally would use the @Value annotation. Autowired is used to inject beans, which you can do via field injection...

@Autowired
private MyService service;

...via constructor injection...

@Autowired
public Person(MyService service) { ... }

...via setter injection...

@Autowired
public void setMyService(MyService service) {..}

But normally you only autowire beans that way. Strings are no beans, so you have to use @Value...

@Autowired
public Person(@Value('${app.some.property}') final String firstName) {...}

This would inject the configured property of app.some.property into that bean. Of course, this only is good if you actually want to inject something from the application context. If you want to create the Person dynamically, you can use the method above.

Sign up to request clarification or add additional context in comments.

2 Comments

In simple words, I want to create a object of a person class with 2 string properties whenever required. In java we can do that using new but want to undestand the way to create same using spring. @Autowired works well with no argument constructor but how it works with constructor with argunments.
Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.