Acorn academy 01/31 스프링

Bae Seong Jun·2024년 1월 31일

Acorn academy

목록 보기
42/70

configuration.xml 외부파일로 빼두기

logback

콘솔 실행시 로그를 나타내는 것에도 관여함.
로그 기록 레벨 : trace-debug-info- warn-error
trace: 전부표시
error: 에러만 표시

	<root level="trace"><!-- 로그 기록 레벨 : trace-debug-info- warn-error -->
		<appender-ref ref="STDOUT" />
		<appender-ref ref="DAILYOUT" />
	</root>

bean설정이 여러 xml에 나눠져 있을 때

모든 xml 로딩

ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/kkk/*.xml");

person.xml에서 다른 xml들을 로딩하고 main에서는 test만 로딩하는 방식

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<import resource="animal.xml"></import>
	<bean class="com.spring.Person" id="xxx"></bean>
</beans>

main

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.spring.Animal;
import com.spring.Person;

public class PersonTest {
	public static void main(String[] args) {
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/kkk/person.xml");
		Person xxx = ctx.getBean("xxx", Person.class);
		Animal yyy = ctx.getBean("yyy", Animal.class);
		System.out.println(xxx.getInfo()+ ", " + yyy.getName());
	}
}

Dependency Injection

constructor injection (생성자 주입):

<bean>은 기본생성자를 사용함

기본생성자 말고 다른 생성자를 사용하기 위해선 아래와 같이 사용(=매개변수 전달)

<constructor-arg name="매개변수명" value="저장할 매개변수값"></constructor-arg>

생성자로 초기값을 지정해주는 것과 같다.

	<bean class="com.spring.Person" id="kkk">
		<constructor-arg name="x" value="홍길동"></constructor-arg>
		<!-- <constructor-arg name="age"></constructor-arg> -->
	</bean>
    
    <!-- 아래 자바코드와 같은 기능
	Person kkk = new Person("홍길동"); -->

주의사항 매개변수 이름 맞춰야함
value가 int형 등 String 타입이 아니라도 ""쌍따옴표로 묶어야한다.

자동형변환

bean에서 매개변수를 넣을 때 value=""는 실제 멤버변수가 어떤 데이터타입이든 자동형변환을 해준다. 다만 객체는 ref를 써야한다.

ref

bean에서 객체를 생성할 때 매개변수로 객체를 설정하고 싶을 때 value=""대신 ref=""를 사용한다. 여기서 cat bean은 어디에 선언되든 상관없지만 위에 선언되는 것이 권장된다.

	<bean class="com.spring.Cat" id="pet01">
		<constructor-arg name="catName" value="야옹이"></constructor-arg>	
		<constructor-arg name="catAge" value="20"></constructor-arg>	
	</bean>
	<bean class="com.spring.Person" id="xxx">
		<constructor-arg name="username" value="홍길동"></constructor-arg>
		<constructor-arg name="age" value="10"></constructor-arg>
		<constructor-arg name="cat" ref="pet01"></constructor-arg>
	</bean>

Main - service - dao 구조 new를 bean으로 바꾸기

profile
코딩 프로?

0개의 댓글