Java 将自定义对象传递到Spring引导控制器
我目前正在用Java编写SpringBootRESTAPI 我的切入点如下:Java 将自定义对象传递到Spring引导控制器,java,spring,spring-boot,Java,Spring,Spring Boot,我目前正在用Java编写SpringBootRESTAPI 我的切入点如下: public static void main(String[] args) { // Starting Spring application ConfigurableApplicationContext context = SpringApplication.run(Monolith.class, args); } 它成功地创建了控制器 但是,我现在有一个RedisCache对象,我希望将其
public static void main(String[] args) {
// Starting Spring application
ConfigurableApplicationContext context = SpringApplication.run(Monolith.class, args);
}
它成功地创建了控制器
但是,我现在有一个
RedisCache
对象,我希望将其传递到这些控制器中。此RedisCache
对象需要在ConfigurableApplicationContext
之前手动实例化(使用正确的用户名、密码、地址、端口和超时),我不确定如何正确地将此缓存注入控制器。您应该实现拦截器,并使用预句柄将其注入到ThreadContext中
更多信息:
谢谢您应该实现拦截器,并使用预句柄将其注入到ThreadContext中 更多信息:
谢谢我通过创建如下配置类解决了这个问题:
@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;
}
除非这种方法存在根本性的问题,否则它似乎是我的最佳解决方案。我可以通过创建如下配置类来解决这个问题:
@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;
}
除非这种方法存在根本性的问题,否则它似乎是我的最佳解决方案