Day68 :) 스프링 빈

Nux·2021년 12월 27일
0

자바웹개발

목록 보기
82/105
post-thumbnail

Spring Bean

  • Spring IoC Container에 의해 생성, 관리, 인스턴스화 되는 자바객체
  • 보통 싱글턴 형식을 띠고 있음

싱글턴

  • 인스턴스가 오직 1개만 생성되는 패턴
  • 전역 변수 사용 없이 하나의 객체만 생성해서 이를 어디든지 참조할 수 있도록 하는 것. 최초로 생성자를 만든 후 이후 호출된 생성자는 최초의 생성자가 만든 객체를 리턴
public class Singleton {

    private static Singleton self = new Singleton();

	private Singleton() {}

    public static Singleton getInstance() {
        return self;
    }
}

// 이후 생성자 호출 시
Singleton singleton = Singleton.getInstance();
// 객체(인스턴스)를 새로 생성하지 않음
  • 인스턴스를 한개만 생성하므로 메모리를 아낄 수 있음
  • 데이터 공유가 쉬움

빈 등록하기

  • 스프링 컨테이너에 빈 생성/조립에 대한 정보를 전달하기 위해 정의

xml 설정파일로 등록

  • pom.xml으로 스프링 버전 정의
  • resources에 application.xml 생성해서 생성할 Bean객체 명시

setter로 주입

  • 빈으로 등록할 클래스에 setter가 존재해야 값 설정 가능
<beans>
	<bean id="식별자명" class="빈으로 등록할 클래스 경로">
    	 <property name="값을 set할 변수" value="" />
    </bean>
</beans>
  • id: 빈을 식별하기 위한 고유 이름
  • class: 빈으로 등록할 클래스 경로. 객체화 할 개체(entity or vo)
  • name: 값을 set할(의존성 주입받을) 변수
  • value: name에 들어갈 값
<beans>
	<bean id="student1" class="com.example.Student">
    	<property name="name" value="홍길동" />
    </bean>
</beans>

Student student1 = new Student();
student1.setName("홍길동");

<beans>
	<bean id="식별자명1" class="빈으로 등록할 클래스 경로1">
    
    <bean id="식별자명2" class="빈을 등록할 클래스 경로2">
    	<property name="값을 set할 변수" ref="식별자명1" />
    </bean>
</beans>
  • name: 값을 set 할(의존성을 주입받을) 변수명
  • ref: 의존성이 주입되는 빈 이름 (매개변수로 전달되는 객체 이름)
<beans>
	<bean id="maleStudent" class="com.example.maleStudent">
    
    <bean id="student1" class="com.example.Student">
    	<property name="name" ref="maleStudent">
    </bean>
</beans>

Student student1 = new Student();
student1.setName(maleStudent());

참조형 변수를 property로 설정할 때는 ref, 기본형 변수를 property로 설정할 때는 value


생성자로 주입

  • 기본 생성자 외의 생성자가 정의되어 있는 경우 사용
  • 의존하는 객체나 값을 생성자의 매개변수를 사용해서 의존성 주입
<beans>
	<bean id="식별자명" class="클래스경로">
    	<constructor-arg value="초기 값" ref="빈 아이디"/>
    </bean>
 </beans>
  • value: 초기화할 값 작성
  • ref: 생성자에 매개변수로 전달될 빈 아이디
1. Student.java
public class Student{

	private String name;
    private int grade;
    private int class;
    
    public Student(String name, int grade, int class){
    	this.name = name;
        this.grade = grade;
        this.class = class;
    }
    
}

2.xml
<bean id="student1" class="com.example.Student">
	<constructor-arg value="조진웅" />
    <constructor-arg value="3" />
    <constructor-arg value="10" />
</bean>

어노테이션을 이용해서 등록

@ComponentScan(basePackages = "z.x.y")
@ComponentScan(basePackageClasses = ApplicationConfig.class)
public class ApplicationConfig {}

@Configuration&@Bean 어노테이션 사용

  • 개발자가 제어 불가능한 외부 라이브러리나 설정을 위한 클래스를 빈으로 등록 시 사용
  • 1개 이상의 @Bean을 제공하는 클래스는 반드시 @Configuration 부착해야함
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ApplicationConfig {
 
    @Bean
    public Test test() {
        return new Test();
    }
 
    @Bean
    public Example example() {
        Example example = new Example();
        example.setTest(test());
        return example;
    }
}
  • @Bean이 부착 된 클래스가 1개 이상이므로 클래스 상단에 @Configuration 어노테이션 부착
  • 빈으로 등록할 객체를 리턴하는 메서드 정의 후 @Bean어노테이션 부착
    • 빈 이름 = 메서드명
    • 빈 타입 = 리턴 타입
    • 빈 레퍼런스 = 리턴하는 객체

@Component 어노테이션 사용

  • 직접 작성한 클래스를 빈으로 등록하기 위한 어노테이션
  • Java 설정 파일 클래스에 @ComponentScan 애노테이션 작성
  • basePackages, basePackageClasses로 패키지 지정
  • @Controller: Controller 클래스에 설정
  • @Service: Service 클래스에 설정
  • @Repository: Dao클래스에 설정

@Autowired

  • 빈을 자동으로 주입해주며 생성자, 필드, 메서드에 적용 가능

예제

  • IoC컨테이너에 빈으로 등록된 객체는 다른 객체에 의존성 주입 가능

Setter Injection

public class HelloService{

	// 주입받는 객체를 담는 필드
	private Greeting greeting;
    
	// 주입받기 위한 setter 메서드   
	public void setGreeting(Greeting greeting){
		this.greeting = greeting;
	}
    
	public void sayHello(){
		greeting.hi();
	}
    
	public class GreetingImpl extends Greeting{
    	public void hi(){
			System.out.println("Hello");
		}
	}
}

<bean id="greetImpl" class="x.y.z.GreetingImpl"/>
<bean id="service" class="x.y.z.HelloService">
	// name: setter 메서드 이름
	// ref: 조립한 빈 이름
    <property name="greeting" ref="greetImpl"/>
</bean>

Constructor Injection

public class Connector {
	private String ip;
	private int port;
	private String username;
	private String password;
					
	public Connector(String username, String password) {
		this.ip = "localhost"; 
		this.port = 1521;
		this.username = username;
		this.password = password
	}
	
	public Connector(String ip, int port, String username, String password) {
		this.ip = ip; 
		this.port = port;
		this.username = username;
		this.password = password
	}	
}
					
<bean class="x.y.z.Connector">
	<constructor-arg name="username" value="hong"/>
	<constructor-arg name="password" value="zxcv1234"/>
</bean>
					
<bean class="x.y.z.Connector">
	<constructor-arg name="ip" value="192.168.10.65"/>
	<constructor-arg name="port" value="2000"/>
	<constructor-arg name="username" value="kim"/>
	<constructor-arg name="password" value="1234zxcv"/>
</bean>

0개의 댓글