Last active
December 10, 2022 04:15
InjectBeanIntoEnumTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MemberType.java | |
@Getter | |
public enum MemberType { | |
GOLD("골드"), | |
SILVER("실버") | |
; | |
private String desc; | |
private MemberDiscountPolicy memberDiscountPolicy; | |
MemberType(String desc) { | |
this.desc = desc; | |
} | |
@Component | |
@RequiredArgsConstructor | |
private static class MemberTypeInjector { | |
private final GoldMemberDiscountPolicy goldMemberDiscountPolicy; | |
private final SilverMemberDiscountPolicy silverMemberDiscountPolicy; | |
@PostConstruct | |
public void postConstruct() { | |
MemberType.GOLD.injectMemberDiscountPolicy(goldMemberDiscountPolicy); | |
MemberType.SILVER.injectMemberDiscountPolicy(silverMemberDiscountPolicy); | |
} | |
} | |
private void injectMemberDiscountPolicy(MemberDiscountPolicy memberDiscountPolicy) { | |
this.memberDiscountPolicy = memberDiscountPolicy; | |
} | |
} | |
// MemberDiscountPolicy.java | |
public interface MemberDiscountPolicy { | |
String getDiscountRate(); | |
} | |
// GoldMemberDiscountPolicy.java | |
@Component | |
@RequiredArgsConstructor | |
public class GoldMemberDiscountPolicy implements MemberDiscountPolicy { | |
@Override | |
public String getDiscountRate() { | |
return "30%"; | |
} | |
} | |
// SilverMemberDiscountPolicy.java | |
@Component | |
@RequiredArgsConstructor | |
public class SilverMemberDiscountPolicy implements MemberDiscountPolicy { | |
@Override | |
public String getDiscountRate() { | |
return "10%"; | |
} | |
} | |
// MemberTypeTest.java | |
@ExtendWith(SpringExtension.class) | |
@SpringBootTest | |
public class MemberTypeTest { | |
@Test | |
@DisplayName("Enum Bean 주입 테스트") | |
public void injectBeanIntoEnumTest() throws Exception { | |
MemberType memberType = MemberType.GOLD; | |
String discountRate = memberType.getMemberDiscountPolicy().getDiscountRate(); | |
Assertions.assertEquals("30%", discountRate); | |
memberType = MemberType.SILVER; | |
discountRate = memberType.getMemberDiscountPolicy().getDiscountRate(); | |
Assertions.assertEquals("10%", discountRate); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment