Configuration 이란?
configuration 은 환경설정을 말한다 .
systen configuration = 시스템 구성도 ㅡ 환경설정 , 세팅
device configuration information (디바이스 구성도 , 환경설정 정보 )
우리가 자주 쓰는 환경설정
(1)Configuraion Management
우리가 프로그래밍을 할 때 반드시 사용해야 하는 configuration management 즉 형상관리
git, svn 이 있다 .
(2) spring (@Configuration) 어노테이션이 있다.
@Configutaion 은 설정파일을 만들기 위한 어노테이션이다
@Bean 을 사용할 때 반드시ㅡ @Configuration 을 활용해서 1개 이상의 Bean 을 생성하고 있음을 명시 해야함
@Configutaion
public class WebMvcConfig implements WebMvcConfigure {
@Bean
Public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
return new ResourceUrlEncodingFilter();
}
@Bean
public HeaderFilter createHeaderFilter() {
return new HeadFilter
}
}
@Configuration은
이 클래스는 스프링이 관리하는 설정 클래스(Configuration class)
여기 안의 메서드들은 Bean(스프링 컨테이너에 등록될 객체) 을 정의합니다
라고 선언하는 역할
즉, XML 설정을 Java 코드로 옮겨놓은 것.
2️⃣ 예시
예: 데이터베이스 설정 클래스
@Configuration
public class AppConfig {
@Bean
public DataSource dataSource() {
return new HikariDataSource();
}
@Bean
public UserService userService() {
return new UserService(dataSource());
}
}
@Configuration을 붙였기 때문에
Spring은 이 클래스를 읽고,
@Bean 메서드에서 리턴하는 객체들을 스프링 컨테이너에 등록합니다.
3️⃣ 내부 동작
Spring은 애플리케이션 실행 시 다음을 합니다:
- @Configuration 클래스를 스캔
- @Bean이 붙은 메서드를 실행하여 객체를 생성
- 생성된 객체를 IoC 컨테이너(ApplicationContext) 에 등록
- 다른 Bean에서 @Autowired나 @Inject로 주입 가능
4️⃣ @Bean과 함께 동작
@Configuration 클래스는 보통 여러 @Bean 메서드를 가집니다.
@Configuration
public class ServiceConfig {
@Bean
public EmailService emailService() {
return new EmailService();
}
@Bean
public UserService userService() {
return new UserService(emailService());
}
}
➡️ 여기서 userService()가 호출될 때
스프링은 같은 클래스의 emailService()를 다시 호출하지 않고,
이미 컨테이너에 등록된 EmailService Bean을 공유해서 사용
(이게 @Configuration의 핵심 특징)
5️⃣ @Configuration vs @Component
구분 @Configuration @Component
| 역할 | 설정 클래스 | 일반 컴포넌트 클래스 |
| 목적 | Bean 등록용 | 일반 빈(서비스, 리포지토리 등) 등록용 |
| 내부 동작 | CGLIB 프록시 사용 (싱글톤 보장) | 일반 클래스 |
| 사용 위치 | Bean 정의하는 설정용 클래스 | Service, Controller, Repository 등 |
💡 @Configuration도 내부적으로는 @Component를 포함.
즉, 컴포넌트 스캔 시 자동으로 등록된다
🔹 6️⃣ 자주 함께 쓰는 어노테이션들
어노테이션 설명
| @ComponentScan | 지정한 패키지의 @Component류(@Service, @Controller 등) 자동 검색 |
| @PropertySource | 외부 설정 파일(application.properties 등) 불러오기 |
| @EnableAutoConfiguration | 스프링 부트가 자동으로 필요한 Bean을 구성하도록 허용 |
| @Import | 다른 Configuration 클래스 불러오기 |
7️⃣ Spring Boot에서의 관계
Spring Boot는 내부적으로 이런 설정 클래스를 자동으로 많이 만들어 둔다.
예를 들어 @SpringBootApplication은 다음을 포함:
@SpringBootConfiguration // 내부적으로 @Configuration
@EnableAutoConfiguration
@ComponentScan
즉,
@SpringBootApplication 자체가 이미 “전역 @Configuration” 역할
✅ 한줄 정리
@Configuration = “이 클래스는 Bean들을 정의하는 설정 클래스다.”
@Bean 메서드들을 모아 스프링 컨테이너에 객체를 등록한다.
(XML 설정의 Java 버전)
💡 1️⃣ @Configuration — 핵심 “환경 설정 클래스” 어노테이션
- 가장 기본적이고 중심이 되는 설정 어노테이션
- 자바 코드로 Bean 등록 (@Bean)
- 예전 XML 설정을 대체한 “자바 설정 클래스” 역할
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
2️⃣ 환경 설정과 함께 자주 쓰이는 “보조적인 환경 관련 어노테이션”
이것들이 함께 쓰이면 진짜 “환경관리 세트”
어노테이션 역할 비고
| @PropertySource | 외부 *.properties 파일을 읽어서 환경변수로 등록 | 환경변수/설정 파일 로드 |
| @EnableAutoConfiguration | 스프링 부트에서 자동 설정 기능 활성화 | 부트 전용 |
| @Profile | 특정 환경(예: dev/test/prod)에만 Bean을 등록 | 환경별 분리 |
| @Import | 다른 Configuration 클래스를 불러오기 | 설정 분리 시 유용 |
| @ComponentScan | 지정된 패키지에서 Component(@Service 등) 자동 탐색 | 스캔 범위 제어 |
| @PropertySources | 여러 설정파일을 한 번에 로드 | @PropertySource 복수 버전 |
| @SpringBootConfiguration | 스프링부트의 루트 설정 (내부적으로 @Configuration 포함) | Boot 자동 구성 핵심 |
| @ConfigurationProperties | application.yml의 속성값을 객체에 매핑 | 실무에서 아주 많이 씀 |
3️⃣ 예시
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "com.example")
public class AppConfig {
@Bean
@Profile("dev") // 개발 환경일 때만 등록
public DataSource devDataSource() {
return new HikariDataSource();
}
@Bean
@Profile("prod") // 운영 환경일 때만 등록
public DataSource prodDataSource() {
return new HikariDataSource();
}
}
➡️ 이런 식으로 환경별 설정, 외부 설정 파일 로드, 빈 등록을 한 클래스에서 관리
이게 바로 스프링의 “환경 관리(configuration management)” 개념
4️⃣ @ConfigurationProperties — 진짜 “환경값 매핑”의 실무 주력
이건 스프링부트 환경관리에서 거의 매일 쓰는 어노테이션
# application.yml
app:
name: MyApp
max-users: 100
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int maxUsers;
// getter/setter
}
➡️ 이렇게 하면 YML의 환경값이 자동으로 자바 객체로 주입
환경관리 측면에선 @ConfigurationProperties가 @Configuration보다 실무에선 더 자주 등장
5️⃣ 한눈 정리
구분 설명 주요 용도
| @Configuration | 설정 클래스 선언 | Bean 등록 |
| @PropertySource | 외부 프로퍼티 파일 로드 | 환경변수 불러오기 |
| @Profile | 환경별 Bean 구분 | dev/prod/test 구분 |
| @Import | 설정 클래스 병합 | 설정 모듈화 |
| @ConfigurationProperties | application.yml 값 매핑 | 환경설정 객체화 |
| @SpringBootConfiguration | Spring Boot 최상위 설정 | Boot 자동 구성 루트 |
✅ 결론
@Configuration은 환경설정의 “뼈대”고,
나머지 어노테이션들은 “세부 환경관리 도구”예요.
즉, 환경관리용 어노테이션은 @Configuration 외에도
@PropertySource, @Profile, @ConfigurationProperties, @Import 등이 존재
그렇다면 xml 파일을 쓸 때와 다른 점은 ?
1️⃣ 과거: 스프링은 “XML 설정” 기반이었다
지금은 자바 코드로 @Configuration, @Bean을 쓰지만
초창기 스프링(2.x~3.x) 에서는 모든 설정을 XML 파일로 했어요.
즉, “어떤 객체(Bean)를 스프링 컨테이너에 등록할지”
그리고 “그 객체들 간의 관계(의존성 주입)” 를
XML 문서로 정의했던 거예요.
2️⃣ 예시
applicationContext.xml
<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">
<!-- UserRepository Bean 등록 -->
<bean id="userRepository" class="com.example.UserRepository" />
<!-- UserService Bean 등록, userRepository 주입 -->
<bean id="userService" class="com.example.UserService">
<property name="userRepository" ref="userRepository" />
</bean>
</beans>
➡️ 여기서 <bean> 태그들이 전부 “스프링 컨테이너에 등록될 객체(Bean)”을 나타낸다
<property>는 UserService 안에 UserRepository를 주입(의존성 주입, DI)하는 설정
그럼 스프링은 이 XML을 어떻게 사용했나?
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = context.getBean("userService", UserService.class);
service.process();
- ClassPathXmlApplicationContext가 XML을 읽음
- <bean> 태그마다 객체를 생성해 IoC 컨테이너에 등록
- 의존성(ref="...")도 자동 주입
즉, XML이 “스프링 컨테이너의 설계도” 역할
4️⃣ XML의 단점 😓
문제점 설명
| 비효율적 | 클래스 이름, 의존성, 프로퍼티를 전부 문자열로 써야 함 |
| 컴파일 타임 체크 불가 | 오타나 타입 불일치도 런타임에야 발견 |
| 복잡함 | 설정이 커지면 수천 줄 XML 관리해야 함 |
| IDE 도움 없음 | 자동완성, 리팩토링 불가 |
| 환경 분리 어려움 | dev/test/prod 설정 나누기가 번거로움 |
5️⃣ 그래서 등장한 게 @Configuration (Java Config)
XML 대신 자바 코드로 Bean 등록하도록 바꾼 것
이전의 XML:
<bean id="userService" class="com.example.UserService" />
➡️ 자바 코드 버전 (@Configuration):
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
이제는 IDE에서 자동완성, 타입체크, 리팩토링이 다 된다
게다가 @Profile, @PropertySource 등으로 환경별 설정도 쉽게 나눌 수 있다.
6️⃣ 정리하면
항목 XML 설정 Java Config (@Configuration)
| 등장 시기 | 스프링 2.x ~ 3.x | 스프링 3.0 이후 |
| 형태 | XML 문서 | 자바 클래스 |
| Bean 등록 방식 | <bean> 태그 | @Bean 메서드 |
| 의존성 주입 | <property> ref | 메서드 호출, 파라미터 |
| 장점 | 코드와 설정 분리 | 타입 안정성, 리팩토링 용이 |
| 단점 | 복잡, 런타임 오류 | 코드화로 약간의 결합도 생김 |
지금은 어떻게 쓰나?
현대 스프링(특히 Spring Boot)에서는 @Configuration + @ComponentScan + @EnableAutoConfiguration
이 세 가지가 합쳐져서 자동 설정 환경이 되어있다
즉, XML은 이제 거의 쓰지 않고
Java Config + YML(application.yml) 조합이 사실상 표준
예전(Spring 2.x~3.x): XML 중심 설정
— 예전에는 XML이 빈 등록의 중심
<!-- applicationContext.xml -->
<bean id="userRepository" class="com.example.UserRepository" />
<bean id="userService" class="com.example.UserService">
<property name="userRepository" ref="userRepository"/>
</bean>
➡️ 스프링이 이 XML을 읽고,
- UserRepository와 UserService 객체를 생성하고
- UserService 안에 UserRepository를 주입(DI)
즉, XML이 스프링 컨테이너의 설계도(Bean 등록소) 역할
중간(Spring 3.x~4.x): Java Config (@Configuration) 등장
XML이 너무 복잡하니까 → 자바 코드로 Bean 등록하자!
@Configuration
public class AppConfig {
@Bean
public UserRepository userRepository() {
return new UserRepository();
}
@Bean
public UserService userService() {
return new UserService(userRepository());
}
}
➡️ 이제 XML 대신 @Configuration 클래스로 Bean 등록과 의존성 주입을 처리
이걸 XML 설정의 자바 버전이라고 부름
지금(Spring Boot 시대): 어노테이션 + 자동 설정 + YAML
지금은 거의 대부분의 프로젝트가 다음 구조예요.
✅ Bean 등록
직접 XML이나 @Bean 안 써도,
@Component 류 어노테이션으로 자동 등록
@Service
public class UserService { ... }
@Repository
public class UserRepository { ... }
➡️ @SpringBootApplication 안의
@ComponentScan이 패키지 아래 모든 @Service, @Repository, @Controller를 자동으로 찾아서 Bean으로 등록해줍니다.
즉, “자동 빈 등록” 구조예요.
✅ 환경 관리
환경 값(설정값, DB 연결, 포트번호 등)은 XML이 아니라
→ application.yml 또는 application.properties로 관리합니다.
# application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: root
password: 1234
profiles:
active: dev
이걸 스프링이 자동으로 읽어서
- @Value("${spring.datasource.url}")
- 또는 @ConfigurationProperties(prefix="spring.datasource")
로 값 주입해준다.
정리 비교표
구분 과거 (XML) 중간 (Java Config) 현재 (Spring Boot)
| Bean 등록 | <bean> 태그 | @Configuration + @Bean | @Component, @Service, @Repository 자동 탐색 |
| 환경 설정 | XML 내 property | @PropertySource + .properties | application.yml or application.properties |
| 의존성 주입 | <property ref=""> | 메서드 파라미터 or @Autowired | @Autowired, 생성자 주입 |
| 실행 진입점 | ClassPathXmlApplicationContext | AnnotationConfigApplicationContext | SpringApplication.run() |
| 특징 | 수동 설정 많음 | 자바 코드 기반, 명시적 설정 | 자동 설정, 환경 분리(dev/test/prod) 용이 |
✅ 예전에는 XML이 Bean 등록소(설정 파일)
✅ 지금은 @Component/@Service 등의 어노테이션으로 자동 등록
✅ 환경 관리는 XML 대신 application.yml 또는 application.properties로 대체
xml 파일은 그럼 마이바티스 쿼리 맵핑용으로도 쓰이는데 역할이 다양한 건가?
1️⃣ XML은 “문법 형식” → 역할이 여러 가지 가능
XML(eXtensible Markup Language)은 데이터 구조를 표현하는 포맷
그래서 “어떤 시스템이 정의하느냐”에 따라 전혀 다른 역할을 할 수 있다
예를 들어 👇
사용처 XML의 역할 예시
| Spring 설정 | Bean 등록 / 의존성 설정 | <bean id="userService" .../> |
| MyBatis 매퍼 | SQL 쿼리 정의 / 매핑 | <select id="findUserById"> ... </select> |
| Android UI | 화면 레이아웃 정의 | <LinearLayout> ... </LinearLayout> |
| Maven 설정 | 빌드 스크립트 정의 | <project><dependencies> ... </dependencies></project> |
👉 즉, XML은 단순한 문서 포맷일 뿐,
“무엇을 정의하느냐는 프레임워크나 툴이 결정하는 것”
2️⃣ YAML은 오직 “환경설정용”으로만 쓰임
반면, YAML(YAML Ain’t Markup Language)은
사람이 읽기 쉬운 설정 파일 포맷으로 설계
- 복잡한 태그가 없고, 들여쓰기로 계층 표현
- Spring Boot, Docker, Kubernetes 등에서 “환경값 설정” 전용으로 사용됨
예:
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: root
password: 1234
server:
port: 8080
➡️ YAML은 어디까지나 값(key-value) 구조만 정의하고
비즈니스 로직, 쿼리, Bean 등록 같은 건 전혀 하지 않는다
⚙️ 3️⃣ 역할 차이 비교
구분 XML YAML
| 정체 | 범용 데이터 표현 언어 | 환경설정 전용 포맷 |
| 역할 | 프레임워크에 따라 다름 (설정, SQL, UI, 빌드 등) | 주로 설정값 관리 |
| 문법 | <태그> 기반, 계층 표현 복잡 | 들여쓰기 기반, 간결 |
| 데이터 표현 | 풍부함 (속성, 네임스페이스 등) | 단순 key-value 계층 |
| 스프링에서 역할 | 과거 Bean 등록용 / MyBatis 쿼리용 | 환경설정(application.yml) |
| 다른 용도 | Android, Maven, HTML 유사 | Docker Compose, K8s 등 |
✅ XML은 “형식”이라서 어떤 시스템이든 설정·데이터·UI 등 다 가능.
✅ YAML은 “환경 설정용 포맷”으로만 사용되며, 코드 실행 로직은 없음.
✅ 스프링에서는 XML이 Bean 등록/SQL 매퍼용,
✅ YAML은 application.yml로 환경값 관리용.
🔸 XML = 범용적인 문서 포맷 (역할 다양)
🔸 YAML = 환경설정 전용 포맷 (Spring Boot, Docker, K8s 등)
'JAVA' 카테고리의 다른 글
| abstract 추상 클래스 or 추상 메서드 (0) | 2025.11.12 |
|---|---|
| Logger , LoggerFactory 를 사용하는 이유 (0) | 2025.11.12 |
| @SuppressWarnings 어노테이션 (0) | 2025.11.12 |
| JDK, JRE ,JVM (0) | 2025.08.28 |
| JAR 와 WAR 의 차이 (0) | 2025.08.28 |