\

해병 코딩

728x90
반응형

개발환경 

스프링 버전 : Spring Tool Suite 3.9.11 

JDK 1.8

톰켓 : 8.5

2021.05.17 - [분류 전체보기] - 스프링 다운로드 /STS 다운로드 (3.9.14 v 다운받기)서블릿/JDK 8 호환

 

스프링 다운로드 /STS 다운로드 (3.9.14 v 다운받기)서블릿/JDK 8 호환

설치 .URL https://github.com/spring-projects/toolsuite-distribution/wiki/Spring-Tool-Suite-3 spring-projects/toolsuite-distribution the distribution build for the Spring Tool Suite and the Groovy/G..

marine1188.tistory.com

2021.03.29 - [JAVA/JAVA(자바)설치 및 툴 이용(ECLIPSE)] - [JAVA] 자바 설치 및 환경 하기 JDK 1.8 버전/ 8버전

 

[JAVA] 자바 설치 및 환경 하기 JDK 1.8 버전/ 8버전

www.oracle.com/kr/java/technologies/javase/javase-jdk8-downloads.html 위 링크 클릭 하면 여기로 온다 각자의 환경에 맞게 설치 하자 나는 윈도우 64 비트 그전 오라클 로그인 필수 1. 다운로든 된거를 실행..

marine1188.tistory.com


 

 

 

 

Main 에서 실행 시키시면 됨니다 

 

기존 스프링 

===========

MainEntry.java

Client.java

porm.xml 

 

 

@Configuration

===========

MainEntry2.java

Client2.java

JavaConfig.java

springconf.xml 

 

@scop // prototype

============

MainPrototype.java

JavaCongigPrototype.java

springconfPrototype.xml

 

 

기존 방식 - xml 파일 설정

Client 클래스

package spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Client implements InitializingBean, DisposableBean {
    /////////////////////////////////////////////////
	public Client(){  //디폴트 생성자
		System.out.println("Client Default");
	}
	
	private String defaulthost;
	
	public Client(String defaulthost){  //매개변수 1개짜리 생성자함수
		this.defaulthost =defaulthost;
		System.out.println("Client 생성자 : " + this.defaulthost);
	}
	////////////////////////////////////////////////////
	
	
	private String host; 

	public void setHost(String host) {
		this.host = host;
		System.out.println("Client.setHost() method 실행");
	}

	
	//afterPropertiesSet : property injection 후에
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("Client.afterPropertiesSet() 실행");
	}

	public void send() {           /* <property name="host" value="서버" /> */
		System.out.println("Client.send() to " + host);    
	}

	
	//DisposableBean 대한 구현부 
	@Override
	public void destroy() throws Exception {         /* ctx.close(); */
		System.out.println("Client.destroy() 실행");
	}
	
}
<?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">

	<bean id="client" class="spring.Client">
		<property name="host" value="서버" />
		<constructor-arg value="Default값"></constructor-arg>
	</bean>

	<!-- <bean id="client2" class="spring.Client2" 
			init-method="connect" destroy-method="close">
		<property name="host" value="서버2" />
	</bean> -->

</beans>

 

xml 파일 기반 실행

package main;

import org.springframework.context.support.GenericXmlApplicationContext;

import spring.Client;


public class MainEntry {
	public static void main(String[] args) {
		
		// xml 기반 설정 파일 이용한 실행
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:springconf.xml");
		
		Client client = ctx.getBean("client", Client.class);
		Client c2 = ctx.getBean("client", Client.class);
		
		client.send();
		ctx.close();  // 스프링 컨테이너 닫기
		
		System.out.println(client.hashCode());
		System.out.println(c2.hashCode());
		
	}
}






 

출력 값

11:03:53.942 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [springconf.xml]
11:03:53.944 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@759ebb3d
11:03:53.975 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'client'
Client 생성자 : Default값
Client.setHost() method 실행
Client.afterPropertiesSet() 실행
Client.send() to 서버
11:03:54.027 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@759ebb3d, started on Wed May 26 11:03:53 KST 2021
Client.destroy() 실행
811587677
811587677

@Configuration  사용

 

설정 파일로 쓸 자바 클래스 생성 

 

package conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import spring.Client2;

@Configuration
public class JavaConfig {

	
	// Client 빈객체로 등록 할때 
	//인터페이스를 구현 하는 코드를 Client2 가 가지고 있지 않아도 
	//초기화 시점 호출될 메소드 
	//소멸될 시점에 호출될 메소드 지정 해서 사용 할 수 있다 
	
	@Bean(initMethod = "connect", destroyMethod = "close")
	public Client2 client2() {
		Client2 client2 = new Client2();
		client2.setHost("서버2");
		return client2;
	}

}







 

Cleint2 클래스 

package spring;

public class Client2 {

	private String host;
	
	public void setHost(String host) {  //DI
		this.host = host;
		System.out.println("Client2.setHost() 실행");
	}

	
	public void connect() throws Exception {
		System.out.println("Client2.connect() 실행");
	}

	public void send() {
		System.out.println("Client2.send() to " + host);
	}

	//
	public void close() throws Exception {
		System.out.println("Client2.close() 실행");
	}

}

 

 

@Configuration 사용 

package main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import spring.Client2;
import conf.JavaConfig;


//java @Configuration 로 설정파일 만드는것
public class MainEntry2 {

	public static void main(String[] args) {
		
		// annotation 기반 설정 파일 이용한 실행 - 자바 코드 작성 위치
		AbstractApplicationContext ctx = 	
				new AnnotationConfigApplicationContext(JavaConfig.class);
		
		Client2 client = ctx.getBean("client2", Client2.class);
		Client2 c2 = ctx.getBean("client2", Client2.class);
		
		client.send();
		ctx.close();
		
		System.out.println(client.hashCode()); // 싱글톤 방식이다
		System.out.println(c2.hashCode());
	}
}

 

출력값

11:30:51.486 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45fe3ee3
11:30:51.500 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
11:30:51.601 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
11:30:51.603 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
11:30:51.605 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
11:30:51.606 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
11:30:51.611 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'javaConfig'
11:30:51.617 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'client2'
Client2.setHost() 실행
Client2.connect() 실행
Client2.send() to 서버2
11:30:51.649 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@45fe3ee3, started on Wed May 26 11:30:51 KST 2021
Client2.close() 실행
1279309678
1279309678

 


스코프 사용 이유

객체의 값을 다르게 이용 하고 싶을때 사용

범위 설정 

스프링은 기본적으로 싱글톤인데 

스코프를 사용 하면 prototype 으로 해서 같은 객체이지만 주소가 다르게 나온다 

package conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import spring.Client2;

@Configuration
public class JavaConfigPrototype {

	@Bean
	@Scope("prototype")
	public Client2 client2() {
		Client2 client2 = new Client2();
		client2.setHost("서버2");
		return client2;
	}

}

MainPrototype.java

package main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import spring.Client;
import spring.Client2;
import conf.JavaConfigPrototype;

public class MainPrototype {

	public static void main(String[] args) {
		useXml();
		useJava();
	}

	private static void useXml() {
		
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:springconfPrototype.xml");
		Client client1 = ctx.getBean("client", Client.class);
		Client client2 = ctx.getBean("client", Client.class);

		System.out.println("xml 설정 prototype: (client1 != client2) -> " + (client1 != client2));

		ctx.close();
		System.out.println(client1.hashCode());
		System.out.println(client2.hashCode());
	}

	private static void useJava() {
		AbstractApplicationContext ctx =
				new AnnotationConfigApplicationContext(JavaConfigPrototype.class);
		Client2 client1 = ctx.getBean("client2", Client2.class);
		Client2 client2 = ctx.getBean("client2", Client2.class);

		System.out.println("java 설정 prototype: (client1 != client2) -> " + (client1 != client2));

		ctx.close();
	}

}

springconfProrotype. 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">

	<bean id="client" class="spring.Client"   scope="prototype">
		<property name="host" value="서버" />
	</bean>

</beans>

출력 값

 

11:08:56.679 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [springconfPrototype.xml]
11:08:56.681 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@4c98385c
Client Default
Client.setHost() method 실행
Client.afterPropertiesSet() 실행
Client Default
Client.setHost() method 실행
Client.afterPropertiesSet() 실행
xml 설정 prototype: (client1 != client2) -> true
11:08:56.753 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@4c98385c, started on Wed May 26 11:08:56 KST 2021
1071097621
1897871865
11:08:56.785 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@71bbf57e
11:08:56.785 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
11:08:56.866 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
11:08:56.867 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
11:08:56.867 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
11:08:56.868 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
11:08:56.871 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'javaConfigPrototype'
Client2.setHost() 실행
Client2.setHost() 실행
java 설정 prototype: (client1 != client2) -> true
11:08:56.890 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@71bbf57e, started on Wed May 26 11:08:56 KST 2021

 

 


728x90
반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band