Spring - Java Configuration

jodbsgh·2022년 4월 19일
0

🍕"Spring"

목록 보기
13/19

Java Configuration

스프링을 이용할 때 xml로만 할 것인지, 어노태이션으로만 할 것인지 정하는 것이 좋다.

섞어서 하는 것은 좋은 방법이 아니다.

오늘은 순수하게 어노태이션만 사용하는 방법을 알아보도록 하자.

기존 코드

//xml 파일 side
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ..>
	<context:component-scan base-package="spring.di.ui" />
    <!--
    패키지를 두개 이상을 설정할 경우
    <context:component-scan base-package="spring.di.ui, spring.di.entity"/>
    -->
    <bean id="exam" class="spring.di.entity.NewlecExam" />
</beans>

////////////// 위의 코드를 아래로 수정 //////////////
//NewlecDIConfig.java side

/*
@configuration을 통해서 xml설정했던 내용들을 어노태이션으로 설정할 수 있게 한다.
패키지를 두개 이상을 설정할 경우는 아래와 같다.
@ComponentsScan({"spring.di.ui", "spring.di.entity"})
*/

@Configuration
@ComponentsScan("spring.di.ui")	
public class NewlecDIConfig
{
    @Bean
    public Exam exam()
    {
    	return new NewlecExam();
        
/* 
함수는 원래 동사로 기입하지만,
Bean 어노태이션이 설정된 메소드 exam은 컨테이너에 담겨졌을 때 이름으로 사용 되는 것,
bean 태그의 id라고 할 수 있음 


즉, NewlecExam() 을 bean으로써 컨테이너에 담겠다.
그 때의 이름이 exam이다.
*/
    }
}

ApplicationContext 생성하기

ApplecationContext context =
		new AnnotationConfigApplicationContext(NewlecAppConfig.class);

// context 변수를 통해서 NewlecAppConfig.class 파일에 있는
// @Bean에 접근할 수 있게 해준다.

profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글