실습 4일차_Component_Scan
Spring Component_Scan
MainClass.java
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;
public class MainClass {
public static void main(String[] args) {
// IoC Container
ApplicationContext ctx =
new GenericXmlApplicationContext("classpath:com/config/user.xml");
UserService service = ctx.getBean("service", UserService.class);
List<String> list = service.list();
System.out.println(list);
}
}
UserDAO.java
package com.dao;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
// @Component // @Component는 전부 Class Level
@Repository("dao")
public class UserDAO {
public UserDAO() {
System.out.println("UserDAO 생성자");
}
// DB 연동 가정
public List<String> list(){
List<String> list = Arrays.asList("고길동", "홍길동", "신길동");
return list;
}
}
UserService.java
package com.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.dao.UserDAO;
// POJO Class
// @Component // @Component는 전부 Class Level
@Service("service")
public class UserService {
@Autowired
UserDAO dao; // property (인스턴스 변수)
public UserService() {
System.out.println("UserService 생성자");
}
public List<String> list(){
return dao.list();
}
}
user.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- @ 어노테이션 활성화 -->
<!-- <context:annotation-config /> --> <!-- empty tag -->
<!-- 내부적으로 <context:annotation-config /> 기능 포함 -->
<!-- 마킹된(Component) Bean들의 Pakage Name 지정 -->
<context:component-scan base-package="com.service, com.dao" /> <!-- empty tag -->
<!-- <context:component-scan base-package="com.*" /> -->
</beans>
<!-- @ 어노테이션 활성화 -->
<context:annotation-config />
* context 활성화 방법
[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭
* 출력 화면
출처
* Component_Scan :
+ 강의 교재
'AI Bootcamp > Spring' 카테고리의 다른 글
[Spring] 실습 4일차_MyBatis_Transaction★ (0) | 2022.03.18 |
---|---|
[Spring] 실습 4일차_MyBatis ★ (0) | 2022.03.18 |
[Spring] 실습 4일차_@Value_resourceBundle (0) | 2022.03.18 |
[Spring] 실습 4일차_@Resource (0) | 2022.03.18 |
[Spring] 실습 3일차_I18N_MessageSource (0) | 2022.03.18 |