简体   繁体   中英

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 .

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?

You can overcome it with Class<T extends MyReq> constructor arg, like this:

public class BeanPropertyRowMapper<T> implements RowMapper<T> {

     private Class<T> mappedClass;

     public BeanPropertyRowMapper(Class<T> mappedClass) {
        initialize(mappedClass);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM