gpt4 book ai didi

java - 当 DataSourceAutoConfiguration.class 被排除在自动配置之外时如何注入(inject) spring.datasource.* 属性

转载 作者:行者123 更新时间:2023-12-02 12:12:24 27 4
gpt4 key购买 nike

我通过以下链接在启动应用程序中实现了 Multi-Tenancy https://dzone.com/articles/spring-boot-hibernate-multitenancy-implementation

为此,我已将 DatasourceAutoconfiguration.class 从 @SpringBootApplication 中排除,如

@SpringBootApplication(
exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableScheduling
@EnableJpaRepositories
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan("com.mps")
public class MpsServiceClientApplication {

问题是,如何将 spring.datasource.tomcat.* 这样的属性注入(inject)到我的自定义数据源中?更准确地说,如何将下面提到的 2 个属性设置为自定义数据源。

spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true

这就是我设置 jpa 属性的方式。

 final Map<String, Object> hibernateProps = new LinkedHashMap<>();
hibernateProps.putAll(this.jpaProperties.getProperties());
final LocalContainerEntityManagerFactoryBean result =
new LocalContainerEntityManagerFactoryBean();
result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
result.setJpaPropertyMap(hibernateProps);

最佳答案

您必须将这些属性注入(inject)到 @Configuration bean 中并在手动创建 Tomcat 数据源时进行设置:

import org.apache.tomcat.jdbc.pool.DataSource;

@Value("${spring.datasource.test-on-borrow}")
private boolean testWhileIdle;
@Value("${spring.datasource.test-while-idle}")
private boolean testOnBorrow;

@Bean
public DataSource dataSource(){
DataSource dataSource = new DataSource();
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestWhileIdle(testWhileIdle);
...
return dataSource;
}

关于java - 当 DataSourceAutoConfiguration.class 被排除在自动配置之外时如何注入(inject) spring.datasource.* 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46441509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com