
interface 클래스를 여러 클래스가 implements 할경우
Food
//긁지않은 개발자
public interface Food {
public void getFoodName();
}
Bibimbap
//긁지않은 개발자
@Component
public class Bibimbap implements Food{
@Override
public void getFoodName() {
System.out.println("비빔밥");
}
}
Hamburger
//긁지않은 개발자
@Component
public class Hamburger implements Food{
@Override
public void getFoodName() {
System.out.println("햄버거");
}
}
Salad
//긁지않은 개발자
@Component
public class Salad implements Food{
@Override
public void getFoodName() {
System.out.println("샐러드");
}
}
Spaghetti
//긁지않은 개발자
@Component
public class Spaghetti implements Food {
@Override
public void getFoodName() {
System.out.println("스파게티");
}
}
FoodType
@Qualifier("출력될 음식 종류")
//긁지않은 개발자
@Component
public class FoodType {
@Autowired
@Qualifier("bibimbap")
private Food food;
public void showFood() {
food.getFoodName();
}
}
자동 주입 가능한 빈이 두 개 이상이면 이를 지정할 수 있는 방법이 필요한데 @Qualifier를 이용하면 주동 주입 대상 빈을 한정할 수 있다.
AppConfig
//긁지않은 개발자
@Configuration
@ComponentScan(basePackages = {"kr.hcat.di.vo"})
public class AppConfig {
}
@ComponentScan(basePackages = {"kr.hcat.di"}) 끝에 .vo 빼도 된다.
kr.hcat.di 들어가는 모든 Packages를 실행 한다.
AppMain (AppConfig .java)
//긁지않은 개발자
public class AppMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
FoodType foodType = context.getBean("foodType",FoodType.class);
foodType.showFood();
context.close();
}
}
실행 결과
비빔밥
xml파일로 실행할 경우
.xml
//긁지않은 개발자
<context:component-scan base-package="PackageName"></context:component-scan>
AppMain
//긁지않은 개발자
public class AppMain {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("XmlName.xml");
FoodType foodType = context.getBean("foodType",FoodType.class);
foodType.showFood();
context.close();
}
}
JavaClass 실행할때
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaClassName.class);
Xml 실행할때
AbstractApplicationContext context = new ClassPathXmlApplicationContext("XmlName.xml");
confilg , xml 파일 없이
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("PackageName");
context.refresh();
@어노테이션 관련 포스팅
https://h0-0cat.tistory.com/entry/XFile-26
[Spring] Spring @Annotation(어노테이션) 이해하기
Class Name 1. VO class 만들기 EmployeeVO //긁지않은 개발자 @AllArgsConstructor //여기에 필드에 쓴 모든생성자만 만들어준다. @NoArgsConstructor //기본 생성자를 만들어준다. @Data // getter, setter 만들어준다. public
h0-0cat.tistory.com

'SPING > Spring 이용하기' 카테고리의 다른 글
[Spring] Spring 기본 Error Page 변경 (0) | 2023.06.25 |
---|---|
[Spring] Spring Boot @JsonFormat 뜻과 사용 방법 (0) | 2023.06.25 |
[Spring] Spring @Component뜻과 사용법 (0) | 2023.06.14 |
[Spring] Spring @Annotation(어노테이션) 이해하기 (0) | 2023.06.13 |
[Spring] Spring 이메일, SNS 메세지 보내기 (0) | 2023.06.13 |