빈은 두 단계로 나눠서 읽힌다.
우선 별도의 프로젝트를 새로 판다.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
public class Holoman {
String name;
int howLong;
@Override
public String toString() {
return "Holoman{" +
"name='" + name + '\'' +
", howLong=" + howLong +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHowLong() {
return howLong;
}
public void setHowLong(int howLong) {
this.howLong = howLong;
}
}
@Configuration
public class HolomanConfiguration {
@Bean
public Holoman holoman() {
Holoman holoman = new Holoman();
holoman.setHowLong(5);
holoman.setName("Keesun");
return holoman;
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
me.whiteship.HolomanConfiguration
기존 프로젝트로 돌아와 의존성을 적용하면 라이브러리가 나타난다.
holoman = Holoman{name='Keesun', howLong=5}
Holoman을 어디서도 정의한 적이 없지만 사용할 수 있게 되었다.
@SpringBootApplication
public class ConceptsOfSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(ConceptsOfSpringBootApplication.class, args);
}
@Bean
public Holoman holoman() {
Holoman holoman = new Holoman();
holoman.setName("whiteship");
holoman.setHowLong(50);
return holoman;
}
}
@Configuration
public class HolomanConfiguration {
@Bean
@ConditionalOnMissingBean
public Holoman holoman() {
Holoman holoman = new Holoman();
holoman.setHowLong(5);
holoman.setName("Keesun");
return holoman;
}
}
다시 설정 프로젝트 쪽으로 돌아가서 @ConditionalOnMissingBean을 달아준다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
holoman.name=whiteship
holoman.how-long=55
@ConfigurationProperties("holoman")
public class HolomanProperties {
private String name;
private int howLong;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHowLong() {
return howLong;
}
public void setHowLong(int howLong) {
this.howLong = howLong;
}
}
@Configuration
@EnableConfigurationProperties(HolomanProperties.class)
public class HolomanConfiguration {
@Bean
@ConditionalOnMissingBean
public Holoman holoman(HolomanProperties properties) {
Holoman holoman = new Holoman();
holoman.setHowLong(properties.getHowLong());
holoman.setName(properties.getName());
return holoman;
}
}