Spring에서는 @Configuration과 @Bean을 활용하여 여러 가지 컴포넌트를 커스텀 설정할 수 있습니다.
대표적으로 데이터 소스, 캐시, HTTP 클라이언트, 메시지 컨버터 등을 설정할 수 있습니다.
Spring Boot는 기본적으로 HikariCP를 사용하지만, 직접 설정할 수도 있습니다.
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("user");
config.setPassword("password");
config.setMaximumPoolSize(10); // 최대 커넥션 수 설정
config.setMinimumIdle(5); // 최소 유지할 커넥션 수
config.setIdleTimeout(30000); // 미사용 커넥션 유지 시간
return new HikariDataSource(config);
}
}
📌 설정한 DataSource가 Spring에서 자동으로 사용됩니다.
📌 HikariCP의 커넥션 풀을 조정하여 성능 최적화 가능
Spring의 RestTemplate을 설정하여 HTTP 요청 시 타임아웃 등 설정할 수 있습니다.
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(3)) // 연결 타임아웃
.setReadTimeout(Duration.ofSeconds(5)) // 읽기 타임아웃
.build();
}
}
📌 HTTP 요청 타임아웃을 설정하여 API 응답 지연 시 오류 방지
Spring WebFlux의 비동기 HTTP 클라이언트인 WebClient도 설정할 수 있습니다.
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient() {
return WebClient.builder()
.baseUrl("https://api.example.com") // 기본 URL 설정
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.clientConnector(new ReactorClientHttpConnector(
HttpClient.create().responseTimeout(Duration.ofSeconds(5))
))
.build();
}
}
📌 WebClient는 RestTemplate보다 비동기 요청에 최적화되어 있음
Spring에서 Redis를 캐시로 활용할 수 있도록 설정할 수 있습니다.
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
📌 Redis를 사용하여 데이터 캐싱 가능
📌 JSON 직렬화를 적용하여 객체를 쉽게 저장 및 조회 가능
Spring에서 JSON 변환을 담당하는 Jackson의 ObjectMapper 설정도 가능합니다.
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
}
📌 알 수 없는 JSON 필드는 무시하고, null 값은 직렬화하지 않도록 설정
Spring Security 없이 CORS를 전역적으로 허용하는 설정을 추가할 수 있습니다.
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
};
}
}
📌 외부 도메인에서 API를 호출할 수 있도록 허용하는 CORS 설정
Spring Security에서 인증 및 권한 설정을 직접 구성할 수 있습니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN") // 관리자만 접근 가능
.requestMatchers("/user/**").authenticated() // 로그인 필요
.anyRequest().permitAll() // 나머지 요청은 모두 허용
)
.formLogin(Customizer.withDefaults()); // 기본 로그인 페이지 사용
return http.build();
}
}
📌 경로별 접근 권한을 설정하고, 로그인 폼을 활성화할 수 있음
Spring AOP를 사용하면 로깅, 트랜잭션 처리 등을 일괄 적용할 수 있습니다.
@Aspect
@Configuration
public class LoggingAspect {
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Before("execution(* com.example.service.*.*(..))") // 서비스 계층 메서드 실행 전 로깅
public void logBefore(JoinPoint joinPoint) {
logger.info("메서드 실행: " + joinPoint.getSignature());
}
}
📌 서비스 계층의 모든 메서드 실행 전에 로그를 출력하도록 설정
Spring에서 파일 업로드를 처리하는 MultipartResolver를 설정할 수 있습니다.
@Configuration
public class FileUploadConfig {
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(10 * 1024 * 1024); // 최대 업로드 크기: 10MB
resolver.setMaxInMemorySize(1 * 1024 * 1024); // 메모리에 저장할 최대 크기: 1MB
return resolver;
}
}
📌 파일 업로드 크기를 제한하여 서버 과부하 방지
Spring에서는 @Configuration과 @Bean을 활용하여 다양한 설정을 직접 관리할 수 있습니다.
대표적인 예시는 다음과 같습니다.
| 설정 대상 | 설명 |
|---|---|
| 스레드 풀 | ThreadPoolTaskExecutor를 설정하여 비동기 처리 최적화 |
| 데이터베이스 (HikariCP) | 커넥션 풀을 직접 설정하여 DB 연결 성능 개선 |
| HTTP 클라이언트 (RestTemplate/WebClient) | 타임아웃 및 기본 헤더 설정 가능 |
| Redis 캐시 | 캐시 저장 방식 및 직렬화 설정 가능 |
| Jackson ObjectMapper | JSON 변환 설정을 커스텀 가능 |
| CORS 설정 | 외부 도메인에서 API 접근을 허용 |
| Spring Security | API 인증 및 권한 설정 가능 |
| AOP 로깅 | 서비스 계층에서 자동으로 로그 출력 가능 |
| 파일 업로드 설정 | MultipartResolver를 설정하여 파일 크기 제한 가능 |
❓ 필요한 설정이 있으면 말씀해 주세요.
💡 특정 환경에 맞게 최적화된 설정을 도와드릴 수 있습니다! 😊