SPING/Spring 이용하기
[Spring] Spring @Component뜻과 사용법
h0-0cat
2023. 6. 14. 01:00
728x90
@Component
@Component 어노테이션을 이용하면 Bean Configuration 파일에 Bean을 따로 등록하지 않아도 사용할 수 있다.
빈 등록자체를 빈 클래스 자체에다가 할 수 있다는 의미이다.
ApplicationUser
//긁지않은 개발자
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component("applicationUser")
public class ApplicationUser {
private String name="최고관리자";
}
Application
//긁지않은 개발자
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component("application")
public class Application {
//@Resource(name = "applicationUser")
@Autowired
private ApplicationUser applicationUser;
}
AppConfig
//긁지않은 개발자
@Configuration
@ComponentScan(basePackages = {"kr.hcat.di.vo"})
public class AppConfig {
}
AppMain(AppConfig)
//긁지않은 개발자
public class AppMain {
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Application application = context.getBean("application",Application.class);
System.out.println(application);
context.close();
}
}
실행 결과
Application(applicationUser=ApplicationUser(name=최고관리자))
Employee
//긁지않은 개발자
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component
public class EmployeeAddress {
private String street="송월길 48";
private String city="서울 종로구";
}
EmployeeAddress
//긁지않은 개발자
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component
public class Employee {
@Autowired
private EmployeeAddress employeeAddress;
}
AppConfig
//긁지않은 개발자
@Configuration
@ComponentScan(basePackages = {"kr.hcat.di.vo"})
public class AppConfig {
}
AppMain
//긁지않은 개발자
public class AppMain {
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Employee employee = context.getBean("employee",Employee.class);
System.out.println(employee);
context.close();
}
}
실행 결과
Employee(employeeAddress=EmployeeAddress(street=송월길48 21, city=서울 종로구))
xml
//긁지않은 개발자
<context:component-scan base-package="PackgeName"></context:component-scan>
AppMain
//긁지않은 개발자
AbstractApplicationContext context = new ClassPathXmlApplicationContext("XmlName.xml");
@어노테이션 관련 포스팅
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
728x90