有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将自定义对象传递到Spring引导控制器

我目前正在用Java编写Spring Boot REST API

我有一个切入点如下:

  public static void main(String[] args) {
    // Starting Spring application
    ConfigurableApplicationContext context = SpringApplication.run(Monolith.class, args);
  }

它成功地创建了控制器

然而,我现在有一个RedisCache对象,我希望将其传递给这些控制器。这个RedisCache对象需要在ConfigurableApplicationContext之前手动实例化(使用正确的用户名、密码、地址、端口和超时),我不确定如何正确地将这个缓存注入控制器


共 (2) 个答案

  1. # 2 楼答案

    我可以通过创建这样的配置类来解决这个问题:

    @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;
      }
    

    并通过在控制器中自动连接构造函数来注入资源:

      @Autowired
      public MyController(Cache cache) {
        this.cache = cache;
      }
    

    除非这种方法存在根本性的问题,否则它似乎是我的最佳解决方案