반응형
SMALL
[5] 스프링 DI - 객체 속성
환경설정 파일을 만든다
(1) proteotype 과 singleton
prototype : 참조할때마다 새로운 자바빈 객체를 생성하여 주소값이 달라진다
singleton : 참조할때 항상 같은 객체의 주소값을 참조한다 , 생략할수 있다
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
//prototype : 요청할때마다 new bean 객체 생성
<bean id ="car" class ="com.fastcapus.ch3.car" scppe="proteotype"/>
// singleton : 컨테이너 당 하나의 객체만 생성
<bean id ="engine" class ="com.fastcapus.ch3.Engine" scppe="singleton"/>
// singleton은 생략 가능
<bean id ="door" class ="com.fastcapus.ch3.Door"/>
</beans>
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
class Car{}
class Engine{}
class Door{}
public class SpringDiTest {
public static void main(String[] args) {
//환경설정파일
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName.
//Car car = ac.getBean("car", Car.class); 위와 똑같은 다른방법1 (타입도 기재했기때문에 형변환 안해도됨)
//Car car2 = (Car) ac.getBean(Car.class); 위와 똑같은 다른방법2 (타입)
Engine engine = (Engine) ac.getBean("engine"); // byName
Engine engine = (Engine) ac.getBean(Engine.class); // byType - 같은 타입이 3개라서 에러
Door door = (Door) ac.getBean("door");
System.out.println("car = " + car);
}
}
(2) 객체의 속성을 부여한다 : 직접 부여
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id ="car" class ="com.fastcapus.ch3.car">
<bean id ="engine" class ="com.fastcapus.ch3.Engine">
<bean id ="door" class ="com.fastcapus.ch3.Door"/>
</beans>
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
class Car{
// 부여할 속성을 정의한다
String color;
int oil;
Engine engine;
Door[] doors;
public void setColor(String color) {
this.color = color;
}
public void setOil(int oil) {
this.oil = oil;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void setDoors(Door[] doors) {
this.doors = doors;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", oil=" + oil +
", engine=" + engine +
", doors=" + Arrays.toString(doors) +
'}';
}
}
public class SpringDiTest {
public static void main(String[] args) {
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName.
Engine engine = (Engine) ac.getBean("engine"); // byName
Engine engine = (Engine) ac.getBean(Engine.class); // byType - 같은 타입이 3개라서 에러
Door door = (Door) ac.getBean("door");
// 속성 값 적용
car.setColor("red");
car.setOil(100);
car.setEngine(engine);
car.setDoors(new Door[]{ ac.getBean("door", Door.class), (Door)ac.getBean("door")});
System.out.println("car = " + car);
}
}
(3) 객체의 속성을 부여한다 : 파일에 속성 참조
클래스에 입력하는 대신 파일에 속성을 부여하여 참조시킨다
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id ="car" class ="com.fastcapus.ch3.car">
<property name ="color" value="red"/>
<property name ="oil" value="100"/>
<property name ="engine" ref="engine"/>
<property name ="doors">
<array value-type="com.fastcapus.ch3.Door">
<ref bean="door"/>
<ref bean="door"/>
</array>
</property>
</bean>
<bean id ="engine" class ="com.fastcapus.ch3.Engine">
<bean id ="door" class ="com.fastcapus.ch3.Door"/>
</beans>
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
class Car{
String color;
int oil;
Engine engine;
Door[] doors;
public void setColor(String color) {
this.color = color;
}
public void setOil(int oil) {
this.oil = oil;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void setDoors(Door[] doors) {
this.doors = doors;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", oil=" + oil +
", engine=" + engine +
", doors=" + Arrays.toString(doors) +
'}';
}
}
public class SpringDiTest {
public static void main(String[] args) {
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName.
Engine engine = (Engine) ac.getBean("engine"); // byName
Engine engine = (Engine) ac.getBean(Engine.class); // byType - 같은 타입이 3개라서 에러
Door door = (Door) ac.getBean("door");
System.out.println("car = " + car);
}
}
(4) 객체의 속성을 부여한다 : 생성자에 속성 참조
파일에 생성자로 속성을 부여하여 참조시킨다
위에 property 대신에 constructor-arg 생성자를 통해 설정할수도 있다 . 대신 클래스에 생성자를 만들어야한다
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id ="car" class ="com.fastcapus.ch3.car">
<constructor-arg name ="color" value="red"/>
<constructor-arg name ="oil" value="100"/>
<constructor-arg name ="engine" ref="engine"/>
<constructor-arg name ="doors">
<array value-type="com.fastcapus.ch3.Door">
<ref bean="door"/>
<ref bean="door"/>
</array>
</constructor-arg>
</bean>
<bean id ="engine" class ="com.fastcapus.ch3.Engine"/>
<bean id ="door" class ="com.fastcapus.ch3.Door"/>
</beans>
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
class Car{
public Car() {}
public Car(String color, int oil, Engine engine, Door[] doors) {
this.color = color;
this.oil = oil;
this.engine = engine;
this.doors = doors;
}
public void setColor(String color) {
this.color = color;
}
public void setOil(int oil) {
this.oil = oil;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void setDoors(Door[] doors) {
this.doors = doors;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", oil=" + oil +
", engine=" + engine +
", doors=" + Arrays.toString(doors) +
'}';
}
}
public class SpringDiTest {
public static void main(String[] args) {
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName.
Engine engine = (Engine) ac.getBean("engine"); // byName
Engine engine = (Engine) ac.getBean(Engine.class); // byType - 같은 타입이 3개라서 에러
Door door = (Door) ac.getBean("door");
System.out.println("car = " + car);
}
}
(5) 객체의 속성을 부여한다 : component-scan , Autowired , Value
<?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.xsd">
<context:component-scan base-package="com.fastcampus.ch3">
//ch3에 있는 같은 이름의 car가 있어서 충돌났음 . 제외하라는 명령어
<context:exclude-filter type="regex" expression="com.fastcampus.ch3.diCopy*.*"/>
</context:component-scan>
<context:annotation-config/>
</beans>
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
@Component("engine") class Engine{}
// <bean id="engine" class="com.fastcampus.ch3.Engine"/> 와 같다
@Component class SuperEngine extends Engine {}
@Component class TurboEngine extends Engine{}
@Component class Door{}
@Component
class Car{
@Value("red") String color;
@Value("100") int oil;
@Autowired Engine engine;
// byType - 타입으로 먼저 검색, 여러개면 이름으로 검색. - superEngine, turboEngine
@Autowired Door[] doors;
public Car() {} // 기본 생성자를 꼭 만들어주자
public Car(String color, int oil, Engine engine, Door[] doors) {
this.color = color;
this.oil = oil;
this.engine = engine;
this.doors = doors;
}
public void setColor(String color) {
this.color = color;
}
public void setOil(int oil) {
this.oil = oil;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void setDoors(Door[] doors) {
this.doors = doors;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", oil=" + oil +
", engine=" + engine +
", doors=" + Arrays.toString(doors) +
'}';
}
}
public class SpringDiTest {
public static void main(String[] args) {
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName. 아래와 같은 문장
Car car = ac.getBean("car", Car.class); // byName
Car car2 = (Car) ac.getBean(Car.class); // byType
Engine engine = (Engine) ac.getBean("engine"); // byName
//Engine engine = (Engine) ac.getBean(Engine.class);
// byType - Engine.class 으로 같은 타입이 3개라서 에러가뜸 (engine, superEngine,turboEngine)
Door door = (Door) ac.getBean("door");
car.setColor("red");
car.setOil(100);
car.setEngine(engine);
car.setDoors(new Door[]{ ac.getBean("door", Door.class), (Door)ac.getBean("door")});
System.out.println("car = " + car);
}
}
만약에 engine이 Component가 되지 않는다면
@Autowired할때 engine은 검색되지 않고 , superEngine 과 turboEngine 만 검색되므로 Engine의 키 값인 engine을 찾을수 없어 오류가 뜬다. 이경우 어떤 타입이 우선인지 @Qualifier를 입력한다
package com.fastcampus.ch3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
class Engine{}
@Component class SuperEngine extends Engine {}
@Component class TurboEngine extends Engine{}
@Component class Door{}
@Component
class Car{
@Value("red") String color;
@Value("100") int oil;
@Autowired
@Qualifier("superEngine") Engine engine;
/*위와 같은 type으로 찾는 방식 대신 아래의 name으로 찾는 방식도 사용가능하다
@Resouce(name="superEngine") Engine engine;
*/
@Autowired Door[] doors;
public Car() {}
public Car(String color, int oil, Engine engine, Door[] doors) {
this.color = color;
this.oil = oil;
this.engine = engine;
this.doors = doors;
}
public void setColor(String color) {
this.color = color;
}
public void setOil(int oil) {
this.oil = oil;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void setDoors(Door[] doors) {
this.doors = doors;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", oil=" + oil +
", engine=" + engine +
", doors=" + Arrays.toString(doors) +
'}';
}
}
public class SpringDiTest {
public static void main(String[] args) {
ApplicationContext ac = new GenericXmlApplicationContext("config.xml");
Car car = (Car) ac.getBean("car"); // byName. 아래와 같은 문장
Car car = ac.getBean("car", Car.class); // byName
Car car2 = (Car) ac.getBean(Car.class); // byType
Engine engine = (Engine) ac.getBean("engine"); // byName
//Engine engine = (Engine) ac.getBean(Engine.class);
// byType - Engine.class 으로 같은 타입이 3개라서 에러가뜸 (engine, superEngine,turboEngine)
Door door = (Door) ac.getBean("door");
car.setColor("red");
car.setOil(100);
car.setEngine(engine);
car.setDoors(new Door[]{ ac.getBean("door", Door.class), (Door)ac.getBean("door")});
System.out.println("car = " + car);
}
}
반응형
LIST
'🌈 백엔드 > 스프링 프레임워크' 카테고리의 다른 글
스프링_외부파일 properties 연결 (feat, @Value) (0) | 2023.09.01 |
---|---|
스프링_OOP 5대 설계원칙 - S O L I D (0) | 2023.08.12 |
스프링_ DB 데이터 객체 DAO (0) | 2023.07.20 |
스프링_테스트_JUnit (0) | 2023.06.28 |
스프링_DAO + Transaction 트랜잭션 (0) | 2023.06.27 |