![](/img/trans.png)
[英]Pass custom json object in swagger with spring boot
[英]Pass custom object into Spring Boot Controller
我目前正在编写 Spring Boot REST API in ZD52387880E1EA22817A972D7
我有一个入口点如下:
public static void main(String[] args) {
// Starting Spring application
ConfigurableApplicationContext context = SpringApplication.run(Monolith.class, args);
}
成功创建了控制器。
但是,我现在有一个RedisCache
object,我希望将其传递给这些控制器。 这个RedisCache
object 需要在ConfigurableApplicationContext
之前手动实例化(使用正确的用户名、密码、地址、端口和超时),我不确定如何正确地依赖注入这个缓存到控制器中。
您应该实现拦截器并将其注入带有预句柄的 ThreadContext
更多信息: https://www.tutorialspoint.com/spring_boot/spring_boot_interceptor.htm
谢谢
我可以通过像这样创建配置 class 来解决这个问题:
@Configuration
public class MyConfiguration {
private CacheFactory cacheFactory;
@Bean(name = "cache")
public CacheFactory cacheFactory() {
if (this.cacheFactory == null) {
this.cacheFactory = new CacheFactory ();
}
return this.cacheFactory;
}
}
工厂看起来像:
public class CacheFactory implements FactoryBean<Cache> {
private final Cache cache;
public CacheFactory() {
this.cache = new Cache(new RedisSettings(
"localhost",
6379,
"pass",
10
));
}
@Override
public Cache getObject() {
return this.cache;
}
@Override
public Class<Cache> getObjectType() {
return MonolithCache.class;
}
并通过自动装配 controller 中的构造函数来注入资源:
@Autowired
public MyController(Cache cache) {
this.cache = cache;
}
除非这种方法存在根本性的问题,否则它似乎是我的最佳解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.