단순 코드 기록/Spring

Spring_context-scan

일일일코_장민기 2024. 2. 8. 13:24
728x90
person.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 check
- 클래스에 달린 @Component를 자동으로 bean 생성
- annotation-config포함
- com.service기준 하위 패키지 전부

 -->

<context:component-scan base-package="com.*"/>


</beans>

 

 

 

OneService

 

package com.service;

import org.springframework.stereotype.Service;

@Service("xxx")
public class OneService {

public void one() {
System.out.println("oneService");
}

public OneService() {
super();
System.out.println("one");
}

}

 

TwoService

 

package com.service;

import org.springframework.stereotype.Service;

@Service
public class TwoService {

public void Two() {
System.out.println("TwoService");
}

public TwoService() {
super();
System.out.println("two");
}

}

 

 

EchoBean

package com.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.service.OneService;
import com.service.TwoService;

@Component("echoBean")
public class EchoBean {

@Autowired
private OneService one;
@Autowired
private TwoService two;

@Override
public String toString() {
return "EchoBean [one=" + one + ", two=" + two + "]";
}

public EchoBean() {
super();
System.out.println("echo");
}

public EchoBean(OneService one, TwoService two) {
super();
this.one = one;
this.two = two;
}

public OneService getOne() {
return one;
}
public void setOne(OneService one) {
this.one = one;
}
public TwoService getTwo() {
return two;
}
public void setTwo(TwoService two) {
this.two = two;
}
}

 

 

 

Main

package com.spring;

import org.springframework.context.support.GenericXmlApplicationContext;

import com.bean.EchoBean;

public class Main {

public static void main(String[] args) {

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/echo.xml");
EchoBean echo = (EchoBean)ctx.getBean("echoBean");
System.out.println(echo.getOne());
System.out.println(echo.getTwo());

}
}

 

 

 

 

 

 

 

 

com이하의 @component가 달린 클래스는 자동으로 Bean을 생성
Main에서 DTO를 불러오면, 그 DTO는 자동으로 Bean 생성 + Autowired로 인해 자동주입
--> xml에 입력하지 않아도 자동으로 다른 class의 정보를 받아올 수 있음

 

'단순 코드 기록 > Spring' 카테고리의 다른 글

Spring_MVC_Annotation  (0) 2024.02.08
Spring_MVC  (0) 2024.02.08
Spring_SpEL  (0) 2024.02.08
Spring_Value  (0) 2024.02.08
Spring_@Resource  (0) 2024.02.08