![](/img/trans.png)
[英]How to dynamically inject different implementation for the same Interface using spring
[英]Sprint Data Use Multiple Data Modules To Inject Same Interface with Different Implementation at Runtime
我正在尝试在一个项目上实现多个 Spring 数据模块,并选择在运行时使用哪种类型的数据模块(JPA 或 JDBC)。
经过多次尝试,我达到了这个实现:
@Configuration
@Profile("jpa")
@EnableJpaRepositories(basePackages = "com.example.repository.jpa")
public class JpaConfiguration {
@Autowired
public ExampleInterface example;
@Bean
public ExampleInterface example(){
return this.example;
}
}
@Configuration
@Profile("jdbc")
@EnableJdbcRepositories(basePackages = "com.example.repository.jdbc")
public class JdbcConfiguration {
@Autowired
public ExampleInterface example;
@Bean
public ExampleInterface example(){
return this.example;
}
}
@NoRepositoryBean
public interface ExampleInterface extends CrudRepository<Example,String> {
}
package com.example.repository.jdbc;
@Repository
public interface ExampleJdbcInterface extends ExampleInterface, CrudRepository<Example, String> {
}
package com.example.repository.jpa;
@Repository
public interface ExampleJpaInterface extends ExampleInterface, JpaRepository<Example, String> {
}
@RestController
public class ExampleController {
@Autowired
private ExampleInterface repo;
public ExampleController(){
}
}
在我的 application.properties 上,我有 spring.profiles.active=jdbc
但是当我运行应用程序时,日志显示
The following profiles are active: jdbc
这是它应该做的,所以没关系,但也:
Multiple Spring Data modules found, entering strict repository configuration mode!
然后 Spring 尝试查找 Jdbc 和 Jpa 的实体,并假定 JPA 作为默认值。 我能做什么?
在这上面浪费了很多时间,这很容易.. 配置您的 application.properties
spring.data.jpa.repositories.enabled=false
spring.data.jdbc.repositories.enabled=true
完毕! 现在它将返回一个 JPA 或一个 JDBC 实例。 你甚至不需要有单独的接口来扩展一个公共接口,只需创建一个扩展 CrudRepository 就可以了。
编辑:另一种方法
不在 application.properties 上使用那个标志,只使用 spring.profiles.active=jdbc(例如)删除我的配置类并为每个接口放置@Profile(就像我的例子一样,ExampleJdbcInterface 将有 @Profile("jdbc") 和 ExampleJpaInterface将有@Profile("jpa"). 现在将 enablerepositories 添加到主类,这意味着它会像:
@SpringBootApplication
@EnableJdbcRepositories(basePackages="com.example.repository.repository.jdbc")
@EnableJpaRepositories(basePackages="com.example.repository.repository.jpa")
public class ExampleApplication {
现在 Spring 将只查找具有正确配置文件的接口(很可能我的示例不起作用,因为我只有配置中的配置文件,所以他无论如何都在尝试查找所有存储库,这样做将解决问题因为他只会“查找”一个实例。此外,还需要启用存储库,否则他会尝试默认为 JPA,即使只有包 jdbc 的接口使用 @Profile 激活)
这个解决方案有一个优点:假设我们想为我们的存储库添加一个方法。 通过这种方式,我们可以在每种技术上创建自定义接口和相应的实现,然后每个接口将扩展该方法的自定义实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.