1

I am trying to learn constructor injection using Spring 4.3.

I am having class structure is stated below.

@Component     
public class Student {    

private Address address;
private City city;

public Student(Address address, City city) {
    this.address = address;
    this.city = city;
}

public Student(City city, Address address) {
    this.address = address;
    this.city = city;
}

public Student(City city) {
    this.city = city;
}

public Student(Address address) {
    this.address = address;
}
}

Java Based configuration class:

@Configuration
@ComponentScan(basePackages = "com.spring.ConstructorInjection")
public class StudentConfiguration {

}

Client code:

   ApplicationContext context = new  AnnotationConfigApplicationContext(StudentConfiguration.class);
   Student student = context.getBean(Student.class);
   System.out.println(student.getCity());
   System.out.println(student.getAddress());

How can I structure my java based configuration class to assure that a specific constructor will be injected?

Chinmaya
  • 179
  • 1
  • 11
  • Are Address and City other spring beans? If so, Add an `@Autowired` annotation on the constructor you want Spring to use. Not sure why you would need all the other constructors, though. – JB Nizet Nov 05 '16 at 22:41
  • Yes Address and city are spring beans. I might have multiple requirements where we will need multiple constructors. In that how we can configure? – Chinmaya Nov 06 '16 at 03:51
  • Those requirements don't make much sense. People making requirements shouldn't care about the number of constructors and classes developers choose to use to make the application work as demanded. I don't understand your last question. – JB Nizet Nov 06 '16 at 07:41

1 Answers1

0

Depends on how you want you can create bean along with profile, which you would be able to activate at run time

@Configuration
@ComponentScan(basePackages = "com.spring.ConstructorInjection")
public class StudentConfiguration {

//occasion live
@Bean
@Profile("live")
public Student getStudent(Address address, City city){
    return new Student(address,city);
}

//occasion test
@Bean
@Profile("test")
public Student getStudent(Address address){
    return new Student(address);
}


//occasion throwaway
@Bean
@Profile("throwaway")
public Student getStudent(City city){
    return new Student(city);
}

}

//make sure your Address , City annotated with component and component scan is enabled for its packages

kuhajeyan
  • 10,727
  • 10
  • 46
  • 71