我想根据某些情况在Springboot Service类中加载数据库类型(Cassandra或MongoDB)。为此,我打算使用https://sivalabs.in/2016/03/how-springboot-autoconfiguration-magic/中提到的@Conditional注释。
就我而言,我正在扩展org.springframework.stereotype。存储库界面,用于创建如下所示的存储库。
在服务类中,如何基于application.yml中的配置文件或配置获取Cassandra Type或Mongo Type的实例?
谢谢 灰烬
@Repository
public interface CartCassandraRepository extends CrudRepository<com.cassandra.Cart,String> {
}
@Repository
public interface MongoCassandraRepository extends CrudRepository<com.mongo.Cart,String> {
}
这是我的com.cassandra.Cart.java
import org.springframework.data.cassandra.core.cql.PrimaryKeyType;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn;
@Table("Cart")
public class Cart {
@PrimaryKeyColumn(ordinal = 0,type = PrimaryKeyType.PARTITIONED)
@GeneratedValue(strategy = GenerationType.AUTO)
protected String id;
@PrimaryKeyColumn(ordinal = 1,type = PrimaryKeyType.PARTITIONED)
private String userId;
@PrimaryKeyColumn(ordinal = 2,type = PrimaryKeyType.CLUSTERED,ordering = Ordering.DESCENDING)
private String productId;
}
这是我的com.mongo.Cart.java
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field
@Document(collection = "Cart")
public class Cart {
@Id
protected String id;
@Indexed(unique = true)
@Field(value = "UserId")
private String userId;
@Field(value = "ProductId")
private String productId;
}
这是服务类
public class CartServiceImpl{
@Autowired
CassandraCartRepository cassandraCartRepository;
@Autowired
MongoCartRepository mongoCartRepository;
public Cart save(CartDTO cart){
// based on configuration or profile load com.mongo.Cart or com.cassandra.Cart
// based on the configuration or profile do mongoCartRepository.save(cart) or cassandraCartRepository.save(cart)
}
}