JAVA/JAVA개발자 양성과정

[Spring/Maven] @Value로 값 주입하기, 다양한 방식 값 주입

728x90
반응형

👩‍💻 자바 개발자 양성과정 50일차

  1. XML로 연결
  2. 값 주입하기
  3. Annotation로 연결하고 @Value로 값 주입하기
  4. 다양한 방식으로 연결 / 값 주입 / 실행

 

- 연결하는 방식은 xml과 Annotation이렇게 두가지 방식이다.

- Bean을 정하는 방식은 xml에 태그를 쓰는 방법과 Annotation을 쓰는 방법 두가지가 있다.

Annotation 방법에서  compont 을 하게되면 class에 붙혀서 "너 자체가 빈이야!"라고 지정할수있다.

(=스스로를 빈이라고 할수있다)


 

 

 

💗 XML로 연결/값 주입하기

 

src > com.example > Employee.java

package com.example;

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

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString 
//빈 생성자
@NoArgsConstructor
//모든게 들어간 생성자
@AllArgsConstructor
//null인것만 들어가는 생성자
@RequiredArgsConstructor
public class Employee {
	//@NonNull은 생성자 메서드 만들때, 이 두개만 들어간 생성자 메서드가 만들고 싶을때
	private @NonNull int empno;
	private @NonNull String ename;
	private double salary;
	private String job;
}

//빈 생성자
@NoArgsConstructor


//모든게 들어간 생성자
@AllArgsConstructor


//null인것만 들어가는 생성자
@RequiredArgsConstructor


//@NonNull은 생성자 메서드 만들때, 이 두개만 들어간 생성자 메서드가 만들고 싶을때
private @NonNull int empno;

 

 

resources > applicationContext.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:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
	
    <bean id="smith" class="com.example.Employee" c:ename="Smith Pitt" p:job="Daveloper">
		<constructor-arg name="empno" value="7788"></constructor-arg>
		<property name="salary">
			<value>1500</value>
		</property>
	</bean>
</beans>

 

 

src > com.example.test > EmployeeBeanTest

package com.example.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.Employee;
import com.example.EmployeeInfo;
import com.example.config.ApplicationConfig;

import lombok.extern.java.Log;

@Log
public class EmployeeBeanTest {
	public static void main(String[] args) {
		//ApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

		Employee smith = ctx.getBean("smith", Employee.class);
		log.info(smith.toString());
	}
}

EmployeeBeanTest

 

GenericXmlApplicationContext("classpath:applicationContext.xml"); - classpath를 적어주어야한다.
ClassPathXmlApplicationContext("applicationContext.xml"); - classpath를 안 적어주어도 된다

더 공부하기

 

 


💗 Annotation로 연결하고 @Value로 값 주입하기

 

src > com.example > Employee.java

package com.example;

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

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
//빈 생성자
@NoArgsConstructor
//모든게 들어간 생성자
@AllArgsConstructor
//null인것만 들어가는 생성자
@RequiredArgsConstructor

//나는 컴포넌트야, 어딘가에서 나를 부를때 소문자로 시작하게 부름  (애는 employee)
//괄호안에 value="불릴 이름"을 적어줘야함
@Component(value = "smith")
public class Employee {
	// 여기에서 @Value로 직접 값을 넣어줌
	// xml을 하거나 별도의 어노테이션이 필요없는 방법임
	// 스프링에서 쓰는 value임
	@Value("7788")
	// @NonNull은 생성자 메서드 만들때, 이 두개만 들어간 생성자 메서드가 만들고 싶을때
	private @NonNull int empno;
	@Value("Smith Pitt")
	private @NonNull String ename;
	// 정수형도 자동으로 int형으로 포팅됨
	@Value("1500")
	private double salary;
	@Value("Designer")
	private String job;
}

@Component(value = "smith")

- 나는 컴포넌트야, 어딘가에서 나를 부를때 소문자로 시작하게 부름  (이 경우는 employee)

괄호안에 value="불릴 이름"을 적어줘야 한다.

이번 경우는 "smith" 라고 Component를 지정해준 것임

 

 

resources > applicationContext.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:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
        
	<!-- vlaue로 값을 넣었을때 아래 과정은 필수임 -->
	<context:component-scan
		base-package="com.example"></context:component-scan>
        
</beans>

 

 

src > com.example.test > EmployeeBeanTest

package com.example.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.Employee;
import com.example.EmployeeInfo;
import com.example.config.ApplicationConfig;

import lombok.extern.java.Log;

@Log
public class EmployeeBeanTest {
	public static void main(String[] args) {
    	ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		Employee smith = ctx.getBean("smith", Employee.class);
		log.info(smith.toString());
	}
}

 


💗 AnnotationConfig 연결하고 @Bean값 주입하기

 

src > com.example > Employee.java

package com.example;

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

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor

@Component(value = "smith")
public class Employee {
	private @NonNull int empno;
	private @NonNull String ename;
	private double salary;
	private String job;
}

@Component(value = "smith")

 

 

src > com.example.config > ApplicationConfig.java

package com.example.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.example.Employee;
import com.example.EmployeeInfo;

@Configurable
@ComponentScan(basePackages= {"com.example"})
public class ApplicationConfig {
	@Bean
    //id가 메소드이름이야, 리턴타입이 클래스야
	public Employee smith() { 
    // 컨스트럭쳐인거는 new에 담고 프로퍼티인건 set으로 담음 Employee
		Employee smith = new Employee(7788, "Smith Pitt");
		smith.setSalary(500);
		smith.setJob("SuperDevelper");
		return smith;
	}
}

@Configurable
@ComponentScan(basePackages= {"com.example"})

 

 

src > com.example.test > EmployeeBeanTest

package com.example.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.Employee;
import com.example.EmployeeInfo;
import com.example.config.ApplicationConfig;

import lombok.extern.java.Log;

@Log
public class EmployeeBeanTest {
	public static void main(String[] args) {
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);

		Employee smith = ctx.getBean("smith", Employee.class);
		log.info(smith.toString());
	}
}

ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);

 

 


💗 IoC Container생성을 늘여쓰기 - ctx.load(path); ctx.refresh();

 

src > com.example > Student.java

package com.example;

import java.util.List;

import org.springframework.stereotype.Component;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;


//null인것만 들어가는 생성자
@RequiredArgsConstructor
@ToString
public class Student {
	private @NonNull String name;
	private @NonNull int age;
	private @NonNull List<String> hobbys;
	@Setter private int height;
	@Setter private int weight;
}

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="student1" class="com.example.Student"> <constructor-arg value="백두산" 
		/> <constructor-arg value="25" /> <constructor-arg> <util:list> <value>독서</value> 
		<value>영화감상</value> <value>요리</value> </util:list> </constructor-arg> <property 
		name="height" value="165" /> <property name="weight"> <value>45</value> </property> 
		</bean>

</beans>

 

src > com.example > MainClass.java

package com.example;

import org.springframework.context.support.GenericXmlApplicationContext;

import lombok.extern.java.Log;
@Log
public class MainClass {
	public static void main(String[] args) {
		//1. IoC Container생성하기
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		
		//2. Meta Configuration File지정하기
		String path = "classpath:applicationContext.xml";
		ctx.load(path);
		ctx.refresh();
		
		// 3.Bean 생성하기
		Student jimin = ctx.getBean("student1", Student.class);
		log.info(jimin.toString());
		
		// 4. IoC Container소멸하기
		ctx.close();
	}

}

 

 

 


💗 Compont San방식으로 연결하여 @Vlaue로 값 주입하기

- 기본설정 : compont san방식 / value로 값을 주입

 

 

src > com.example > Student.java

package com.example;

import java.util.List;

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

import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@ToString
@Component(value = "jimin")
public class Student {
	@Value("지민")
	private String name;
	@Value("10")
	private int age;
	@Value("등산,공부,춤추기")
	private List<String> hobbys;
	@Value("160")
	private int height;
	@Value("55")
	private int weight;
}

- Class상단에 @Component Annotation을 명시해줌으로써, 해당 Class가 Component로 설정한다.

"jimin"이라는 Component는 이제 Student를 가르키게된 것이다.

- Spring의 Annotation인 @Vlaue를 사용하여 값을 주입한다.

 

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<!-- @componet찾아라 -->
	<context:component-scan
		base-package="com.example"></context:component-scan>

</beans>

component-scan을 통해 com.exple패키지 에서 @component Annotation이 사용된 곳을 찾는다.

 

 

src > com.example > MainClass.java

package com.example.test;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.example.Student;

import lombok.extern.java.Log;

@Log
class StudentBeanJUnitTest {
	private GenericXmlApplicationContext ctx;

	@BeforeEach
	public void init() {
		//기본 생성자 만들기
		this.ctx = new GenericXmlApplicationContext();
	}

	@Test
	void test() {
		this.ctx.load("classpath:applicationContext.xml");
		this.ctx.refresh();
		Student jimin = ctx.getBean("jimin", Student.class);
		log.info(jimin.toString());
	}

}

 

 


💗 Interface를 이용하여 Bean이 초기화(생성)될 때와 종료될 때를 특정하기

- 기본설정 : compont san방식 / value로 값을 주입

 

src > com.example > Student.java

package com.example;

import java.util.List;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.java.Log;

@NoArgsConstructor
@ToString
@Component(value = "jimin")
@Log
//InitializingBean = 객체 초기화
public class Student implements InitializingBean, DisposableBean{
	@Value("지민")
	private String name;
	@Value("10")
	private int age;
	@Value("등산,공부,춤추기")
	private List<String> hobbys;
	@Value("160")
	private int height;
	@Value("55")
	private int weight;
	
	//InitializingBean
	//객체가 초기화될때 작동되어야 할때 이루어질 것
	@Override
	public void afterPropertiesSet() throws Exception {
		log.info("방금 Student Bean이 생성되었습니다");
	}
	
	//DisposableBean
	//객체가 종료할때 이루어질 것
	@Override
	public void destroy() throws Exception {
		log.info("방금 Student Bean이 소멸되었습니다");
	}
}

implements InitializingBean, DisposableBean 인터페이스의 매서드를 Override함으로써 시작과 끝을 특정한다.

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<!-- @componet찾아라 -->
	<context:component-scan
		base-package="com.example"></context:component-scan>

</beans>

 

 

src > com.example.test > StudentBeanJUnitTest.java

package com.example.test;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.example.Student;

import lombok.extern.java.Log;

@Log
class StudentBeanJUnitTest {
	private GenericXmlApplicationContext ctx;

	@BeforeEach
	public void init() {
		log.info("init()실행");
		//기본 생성자 만들기
		this.ctx = new GenericXmlApplicationContext();
	}

	@Test
	void test() {
		this.ctx.load("classpath:applicationContext.xml");
		this.ctx.refresh();
		Student jimin = ctx.getBean("jimin", Student.class);
		log.info(jimin.toString());
		//언제 종료할건지 알려줌
		this.ctx.close();
	}

}

 

 

 


💗Annotation를 이용하여 Bean이 초기화(생성)될 때와 종료될 때를 특정하기 [Compont San]

- 기본설정 : compont san방식 / value로 값을 주입

 

pom.xml에 javax.annotaion 설치하기

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.3.2</version>
		</dependency>

 

 

추가

 

 

src > com.example > Student.java

package com.example;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.java.Log;

@NoArgsConstructor
@ToString
@Component(value = "jimin")
@Log
//InitializingBean = 객체 초기화
public class Student {
	@Value("지민")
	private String name;
	@Value("10")
	private int age;
	@Value("등산,공부,춤추기")
	private List<String> hobbys;
	@Value("160")
	private int height;
	@Value("55")
	private int weight;

	@PostConstruct
	public void myStart() {
		log.info("PostConstruct - 방금 Student Bean이 생성되었습니다");
	}
	
	@PreDestroy
	public void myEnd() {
		log.info("PreDestroy - 방금 Student Bean이 소멸되었습니다");
	}
}

@PostConstruct Bean이 생성될 때
@PreDestroy Bean이 삭제될 때

 

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<!-- @componet찾아라 -->
	<context:component-scan
		base-package="com.example"></context:component-scan>

</beans>

 

 

 

src > com.example.test > StudentBeanJUnitTest.java

package com.example.test;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.example.Student;

import lombok.extern.java.Log;

@Log
class StudentBeanJUnitTest {
	private GenericXmlApplicationContext ctx;

	@BeforeEach
	public void init() {
		log.info("init()실행");
		//기본 생성자 만들기
		this.ctx = new GenericXmlApplicationContext();
	}

	@Test
	void test() {
		this.ctx.load("classpath:applicationContext.xml");
		this.ctx.refresh();
		Student jimin = ctx.getBean("jimin", Student.class);
		log.info(jimin.toString());
		//언제 종료할건지 알려줌
		this.ctx.close();
	}
}

 

 

체크된 부분에 @PostConstruct  Bean/@PreDestroy로 시작과 끝이 특정된 것을 볼수있다.

 


💗Annotation를 이용하여 Bean이 초기화(생성)될 때와 종료될 때를 특정하기 [XML]

- 기본설정 : xml방식

 

src > com.example > Product.java

package com.example;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.java.Log;

@RequiredArgsConstructor
@ToString
@Log
public class Product {
	private @NonNull String name;
	private @NonNull int price;
	private @Setter String maker;
	private @Setter String color;
	
	@PostConstruct
	public void myStart() {
		log.info("PostConstruct - 방금 Product Bean이 생성되었습니다");
	}
	
	@PreDestroy
	public void myEnd() {
		log.info("PreDestroy - 방금 Product Bean이 소멸되었습니다");
	}
}

 

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<!-- 스프링을 인식을 하는데, 스프링이 아닌애(annotaion = javax꺼임)도 인식해야하기에 적어줌 -->
	<context:annotation-config />
	<bean id="canival" class="com.example.Product" c:name="카니발"
		c:price="200000" p:maker="KIA" p:color="white"></bean>

</beans>

<context:annotation-config />

스프링을 인식을 하는데, 스프링이 아닌애 (annotaion = javax꺼임)도 인식해야하기에 적어줘야한다.

 

<context:annotation-config /> 를 작성하지 않고 실행

만약 <context:annotation-config />를 작성하지 않고 실행하면 Spring이 아닌 것은 인식할 수 없다.

시작 Annotaion(@PostConstruct)과 종료 Annotaion(@PreDestroy)를 인식할수 없다.

그래서 생성/종료가 출력되지 않는다.

 

 

<context:annotation-config /> 를 작성하여 실행

만약 <context:annotation-config />를 작성하면 javax에 속한 Annotaion도 인식이 되기 때문에

생성/종료가 출력된다.

 

 

src > com.example > MainClass.java

package com.example;

import org.springframework.context.support.GenericXmlApplicationContext;

import lombok.extern.java.Log;
@Log
public class MainClass {
	public static void main(String[] args) {
		//1. IoC Container생성하기
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		
		//2. Meta Configuration File지정하기
		String path = "classpath:applicationContext.xml";
		ctx.load(path);
		ctx.refresh();
		
		// 3.Bean 생성하기
		Product canival = ctx.getBean("canival", Product.class);
		log.info(canival.toString());
		
		// 4. IoC Container소멸하기
		ctx.close();
	}
}

 


💗Annotation를 이용하여 Bean이 초기화(생성)될 때와 종료될 때를 특정하기 [Compont Scan & XML ]

- 기본설정 : Compont Scan / xml방식 상관없이 적용됨 (좋은 방법x)

src > com.example > Product.java

package com.example;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.java.Log;

@RequiredArgsConstructor
@ToString
@Log
public class Product {
	private @NonNull String name;
	private @NonNull int price;
	private @Setter String maker;
	private @Setter String color;
	
	
	//@PostConstruct
	public void doStart() {
		log.info("PostConstruct - 방금 Product Bean이 생성되었습니다");
	}
	
	//@PreDestroy
	public void doEnd() {
		log.info("PreDestroy - 방금 Product Bean이 소멸되었습니다");
	}
}

 

 

resources > applicationContext.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:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

<!-- 	대세는 어노테이션인데 마지막걸 배우는 이유는 데이터 베이스 연결할때 destroy-method를 사용하기에 알아야함 -->
	<context:annotation-config />
	<bean id="canival" class="com.example.Product" c:name="카니발"
		c:price="200000" p:maker="KIA" p:color="white"
		init-method="doStart"
		destroy-method="doEnd"></bean>
</beans>

- Bean 안에 init-method="생성될때 실행시킬 메서드" , destroy-method="소멸될때 실행시킬 메서드"를 추가한다.

- 대세는 Annotation인데 해당 방법을 배우는 이유는 데이터 베이스 연결할 때 destroy-method를 사용하기에 알아야 한다.

 

 

src > com.example > MainClass.java

package com.example;

import org.springframework.context.support.GenericXmlApplicationContext;

import lombok.extern.java.Log;
@Log
public class MainClass {
	public static void main(String[] args) {
		//1. IoC Container생성하기
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		
		//2. Meta Configuration File지정하기
		String path = "classpath:applicationContext.xml";
		ctx.load(path);
		ctx.refresh();
		
		// 3.Bean 생성하기
		Product canival = ctx.getBean("canival", Product.class);
		log.info(canival.toString());
		
		// 4. IoC Container소멸하기
		ctx.close();
	}
}

 


💗Annotation Class끼리 값 연결하기

 

첫번째 방법

public class EmployeeInfo {
	//바인딩 할거에요 -> 타입이 같은애를 찾는데요
	@Autowired(required = true)
	//이름은 아래와 같아요
	@Qualifier(value = "smith")
	private Employee employee;
}

두번째 방법

public class EmployeeInfo {
	//이름기준으로 찾음 - 이름이 스미스인애를 찾아
	@Resource(name="smith")
	private Employee employee;
}

세번째 방법

public class EmployeeInfo {
	//@Autowired와 기능은 똑같다.
	@Inject
	@Named(value = "smith")
	private Employee employee;
}

 


💗 lombok을 이용해 특정 변수만 setter을 만들어주기

모든 변수에 setter을 만들어주고 싶을때는 Class상단에 @Setter Annotation을 작성해주면 되지만, 특정한 변수만 setter을 만들어주고 싶을때 해당 방법을 사용하면 된다.

 

package com.example;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@RequiredArgsConstructor
@ToString
public class Product {
	private @NonNull String name;
	private @NonNull int price;
	private @Setter String maker;
	private @Setter String color;
}

color와 maker에만 ser매서드가 생긴걸 확인할수 있다.


💗 Bean Scope = "singleton"/"prototype" (싱글톤/프로토타입)

 

싱글톤

<?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:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="canival" class="com.example.Product" c:name="카니발"
		c:price="200000" p:maker="KIA" p:color="white" init-method="doStart"
		destroy-method="doEnd" scope="singleton"></bean>

</beans>

 scope="singleton"

 

package com.example;

import org.springframework.context.support.GenericXmlApplicationContext;

import lombok.extern.java.Log;
@Log
public class MainClass {
	public static void main(String[] args) {
		//1. IoC Container생성하기
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		
		//2. Meta Configuration File지정하기
		String path = "classpath:applicationContext.xml";
		ctx.load(path);
		ctx.refresh();
		
		// 3.Bean 생성하기
		Product canival = ctx.getBean("canival", Product.class);
		Product sonata = ctx.getBean("canival", Product.class);
		if(canival == sonata) {
			log.info("가타");
		}else {
			log.info("달라");
		}
		
		// 4. IoC Container소멸하기
		ctx.close();
	}

}

ID가 canivalbeanscope상태가 singleton일 때,

canivalsonata가 동일한 bean을 가르키고 있으면 둘은 "동일한 bean을 가르킨다"고 할 수 있다.

 

프로토타입

<?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:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="canival" class="com.example.Product" c:name="카니발"
		c:price="200000" p:maker="KIA" p:color="white" init-method="doStart"
		destroy-method="doEnd" scope="prototype"></bean>
        
</beans>

scope="prototype"

 

ID가 canival bean scope상태가 prototype일 때,

canival sonata가 동일한 bean을 가르키고 있으면 둘은 "각자 다른 bean을 가르킨다"고 할 수 있다.

 

728x90
반응형