[Chapter 03] Spring Bean property 애노테이션 #28
Answered
by
corock
coalong
asked this question in
Chapter 03. Spring Application Basics
-
책에서 @primary 와 @lazy 에 대한 Spring Bean property 애노테이션 설명이 나와있습니다. 읽으면서 @primary 와 @lazy 실제로 사용하는 예시를 알고 싶습니다. 또한, @order도 Spring Bean property 애노테이션으로 비슷한 느낌을 받았는데, 다들 실제로 사용해본 사례가 있는지 궁금합니다. |
Beta Was this translation helpful? Give feedback.
Answered by
corock
Dec 15, 2023
Replies: 1 comment 1 reply
-
실무에서 반면 RoutingDataSource.java import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class RoutingDataSource extends AbstractRoutingDataSource {
public static final String PRIMARY = "primary";
public static final String SECONDARY = "secondary";
@Override
protected Object determineCurrentLookupKey() {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
return SECONDARY;
}
return PRIMARY;
}
} DataSourceConfig.java @Configuration
public class DataSourceConfig {
public static final String ROUTING_DATASOURCE = "routingDataSource";
public static final String PRIMARY_DATASOURCE = "primaryDataSource";
public static final String SECONDARY_DATASOURCE = "secondaryDataSource";
@Bean
@DependsOn(ROUTING_DATASOURCE)
public LazyConnectionDataSourceProxy dataSource(DataSource routingDataSource) {
return new LazyConnectionDataSourceProxy(routingDataSource);
}
/**
* 직접 등록한 빈을 사용하기 위해 {@link Primary} 애너테이션을 사용한다.
*/
@Primary
@Bean
@DependsOn({ PRIMARY_DATASOURCE, SECONDARY_DATASOURCE })
public DataSource routingDataSource(@Qualifier(PRIMARY_DATASOURCE) DataSource primaryDataSource,
@Qualifier(SECONDARY_DATASOURCE) DataSource secondaryDataSource) {
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put(RoutingDataSource.PRIMARY, primaryDataSource);
dataSourceMap.put(RoutingDataSource.SECONDARY, secondaryDataSource);
RoutingDataSource routingDataSource = new RoutingDataSource();
routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(primaryDataSource);
return routingDataSource;
}
@Bean(PRIMARY_DATASOURCE)
@ConfigurationProperties(prefix = "spring.datasource.primary.hikari")
public DataSource primaryDataSource() {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.build();
}
@Bean(SECONDARY_DATASOURCE)
@ConfigurationProperties(prefix = "spring.datasource.secondary.hikari")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.build();
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
JoisFe
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
실무에서
@Primary
애너테이션 사용은 종종 봤는데@Lazy
는 거의 못 봤습니다.@Lazy
애너테이션은 복잡한 초기화 로직을 가지고 있을 때 가끔 사용한다고는 하는데 그렇게 권장되는 방식은 아닌 것 같습니다.반면
@Primary
사용 예시로 CQRS 패턴을DataSource
에 적용할 때, 유용하게 사용할 수 있습니다.아래는
@Primary
애너테이션을routingDataSource
스프링 빈에 적용한 샘플 코드입니다.RoutingDataSource.java