HelloConfiguration.java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
class Person {
private String name;
private int age;
private Address address;
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public Address getAddress() {
return this.address;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
class Address {
private String street;
public Address(String street) {
this.street = street;
}
public String getStreet() {
return this.street;
}
}
@Configuration
public class HelloConfiguration {
@Bean(name = "name")
public String name() {
return "Ranga";
}
@Bean
public int age() {
return 15;
}
@Bean
@Qualifier("myAddress") // 명시적으로 이 bean 을 사용하라고 지정할 수 있도록 Qualifier 를 부여해 둠
public Address address() {
return new Address("Main st. 1");
}
@Bean
@Primary // Address bean 이 2개 이상일 때, 이것을 default 로 함
public Address address2() {
return new Address("Sub st. 2");
}
@Bean
public Person person(String name, int age, @Qualifier("myAddress") Address address) {
return new Person(name, age, address);
}
}
HelloMain.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Arrays;
public class HelloMain {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloConfiguration.class)) {
String name = context.getBean("name", String.class);
System.out.println(name);
Integer age = context.getBean("age", Integer.class);
System.out.println(age);
Person person = context.getBean(Person.class);
System.out.println(person.getAddress().getStreet());
// Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
}
}
}