我想为一个实体实现 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
,不如说是关于带有需要参数和通用类型类的注解的自动配置。我不介意花一些时间来实现它,但是我不知道从哪里开始。
这样的事情是否可能,如果可能,如何实现?
最佳答案
不确定我是否 100% 理解您的意思,但此处的示例代码运行良好,并基于注释创建 beans 运行时。注释也有 som 元数据。
通用接口(interface),稍后将被代理:
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
关于java - RestRepositoryResource 的自动配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503989/