[英]How to provide the classtype for generic classes in spring-boot?
I'd like to create a little framework, and want to provide some default classes that should be loaded is the user does not provide an implementation class. 我想创建一个小的框架,并希望提供一些应该加载的默认类,因为用户没有提供实现类。
This behviour shall be similar to the spring-boot
. 这种行为应类似于
spring-boot
。
Problem: Many of the classes I'd like to create should be generic, and would just required the classtype to be defined by the user. 问题:我想创建的许多类都应该是通用的,并且只需要由用户定义类类型即可。
Anyhow this forces the user to explicit implement each of these classes and provide the classtype. 无论如何,这迫使用户显式实现这些类中的每一个并提供类类型。
Is there any way I could word around this? 我有什么办法可以解决这个问题吗? How could the user provide the classtype that should be used on the generics, without having to explicit implement the generic class?
用户如何提供必须在泛型上使用的类类型,而不必显式实现泛型类? Is that possible?
那可能吗?
framework: 框架:
@Configuration
public class AppConfig {
@Bean
@ConditionalOnMissingBean
public BaseValidator<T extends MyReq> defaultValidator() {
return new BaseValidator<T extends MyReq>();
}
}
custom app: 自定义应用:
@Configuration
@EnableAutoConfiguration
@Import(AppConfig.class)
public CustomConfig {
}
//I'd like to prevent that the user has to implement each generic class as follows: //我想防止用户必须实现每个通用类,如下所示:
@Component
public class MyValidator extends BaseValidator<CustomReq> {
}
Is it possible that the user just provides the CustomReq.class
, and the BaseValidator
is automatically instaniated with that provided classtype? 用户是否可能仅提供
CustomReq.class
,并且BaseValidator
会自动使用提供的类类型实例化?
You can overcome it with Class<T extends MyReq>
constructor arg, like this: 您可以使用
Class<T extends MyReq>
构造函数arg克服它,如下所示:
public class BeanPropertyRowMapper<T> implements RowMapper<T> {
private Class<T> mappedClass;
public BeanPropertyRowMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.