我想为一个实体实现RestRepositoryResource (和一些额外的标准功能)的自动配置。我试图通过在@Configuration
或@SpringBootApplication
注解类上添加注解来实现这一点。
如下所示:
@EnableRestRepo(single="foo", collection="foos",entity=Foo.class, id=String.class)
@SpringBootApplication
public class App{
public void main(String[] args){
SpringApplication.run(App.class,args);
}
}
@Entity
public class Foo{
String id;
String bar;
... getters & setters
}
这应该会设置一个(或者功能类似的,如果需要,我可以创建我自己的端点) @RestRepositoryResource
,如下所示:
@RestRepositoryResource(itemResourceRel = "foo", collectionResourceRel = "foos")
public interface Repo extends CrudRepository<Foo,String> {
@RestResource(rel = "foo")
Foo findOneById(@Param("id") String id);
}
这里的目标是在配置一些基本功能时减少一些样板。显然,这个示例将使用更多的自动配置内容进行扩展,但这应该以类似的方式工作。
这个问题与其说是关于RestRepositoryResource
,不如说是关于带注释的自动配置,这些注释需要参数和泛型类型类。我不介意花一些时间来实现这一点,但是我不知道从哪里开始。
这样的事情可能吗?如果可能,是如何实现的?
发布于 2019-02-11 14:59:46
我不确定我是否100 %地理解了您的意思,但是这里的示例代码运行良好,并且基于注释创建了bean运行时。注释也有som元数据。
泛型接口,将在稍后代理:
public interface GenericRepository<T extends GenericType, Long> extends JpaRepository<GenericType, Long> {
}
要放在不同实体上的注释:
@Target(ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@OverrideAutoConfiguration(enabled = false)
@ImportAutoConfiguration
@Import({RestResourceAutoConfiguration.class})
public @interface EnableRestRepo {
Class<?> entity();
String id();
}
一个可以在运行时注册bean的配置类:
@Configuration
@AutoConfigureAfter(value = WebMvcAutoConfiguration.class)
@ConditionalOnClass({CrudRepository.class})
public class RestResourceAutoConfiguration implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
Reflections reflections = new Reflections("jav");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(EnableRestRepo.class);
for (Class<?> c : annotated) {
EnableRestRepo declaredAnnotation = c.getDeclaredAnnotation(EnableRestRepo.class);
Class<?> entity = declaredAnnotation.entity();
String id = declaredAnnotation.id();
Supplier<GenericRepository> genericRepositorySupplier = () -> (GenericRepository) Proxy.newProxyInstance( // register a proxy of the generic type in spring context
c.getClassLoader(),
new Class[]{GenericRepository.class},
new MyInvocationHandler(entity));
beanDefinitionRegistry.registerBeanDefinition(id + "-" + UUID.randomUUID().toString(),
new RootBeanDefinition(GenericRepository.class, genericRepositorySupplier)
);
}
}
META-INF下的spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
jav.RestResourceAutoConfiguration
https://stackoverflow.com/questions/54503989
复制相似问题