본문 바로가기

스프링

옵션 처리

주입할 스프링 빈이 없어도 동작해야 할 때가 있다.

이때 @Autowired만 사용하면 required 옵션의 기본값이 true로 되어 있어서 자동 주입할 대상이 없으면 오류가 발생한다.

 

자동주입 대상을 옵션으로 처리하는 방법을 하나씩 살펴보자.

 

package com.devjones.web.autowired;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.lang.Nullable;

import com.devjones.web.member.Member;

public class AutowiredTest {

	@Test
	void AutowiredOption() {
		ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
	}
	
	static class TestBean {
		
		@Autowired(required = false)	// 수정자 메소드 자체가 호출x
		public void setNoBean1(Member noBean1) {
			System.out.println("noBean1 : " + noBean1);
		}
		
		@Autowired
		public void setNobean2(@Nullable Member noBean2) {
			System.out.println("noBean2 : " + noBean2);
		}
		
		@Autowired
		public void setNoBean3(Optional<Member> noBean3) {
			System.out.println("noBean3 : " + noBean3);
		}
	}
}

JUnit 테스트 결과

15:55:01.845 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7ba18f1b
15:55:01.858 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
15:55:01.892 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
15:55:01.894 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
15:55:01.895 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
15:55:01.896 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
15:55:01.903 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'autowiredTest.TestBean'
noBean2 : null
noBean3 : Optional.empty

 

정리

* Member는 스프링 빈이 아니다.

* setNoBean1()은 @Autowired(required = false)이므로 호출자체가 안된다.

'스프링' 카테고리의 다른 글

톰캣과 스프링, 그리고 ContextLoaderListener  (0) 2021.06.13
생성자 주입  (0) 2021.04.05
mybatis-spring:scan과 context:component-scan  (0) 2021.03.01
Controller의 리턴타입  (0) 2021.01.01
slf4j 추가하기  (0) 2020.11.08