• 我有一个类 CosmosConnection SupplierGetResponseFeed
  • 我正在从 SupplierGetResponseFeed
  • 调用 CosmosConnection 的方法
  • 我从中调用 CosmosConnection 方法的 SupplierGetResponseFeed 方法是静态
  • 示例:public static SupplierResponseDataEntity prepareSupplierAzureData(Map<String, Object> row, String[] columnNames) {
  • 因此,当我在 SupplierGetResponseFeed 中创建 CosmosConnection 对象时,由于无法从中的bootstrap.yml文件中选择值,所以我无法使用@Autowired。CosmosConnection
  • 尽管我在 Supplier @ ResponseFeed 中使用@Autowired创建对象,但我无法从引导程序中选择值

    @自动连线
    静态CosmosConnection宇宙;

  • 以下是供应商GetResponseFeed 的代码
    public class SupplierGetResponseFeed {
    static CosmosConnection cosmos= new CosmosConnection(); //creating object
    public static SupplierResponseDataEntity prepareSupplierAzureData(Map<String, Object> row, String[] columnNames) {
    //Some code
    cosmos.connectToDB(); //calling the method of CosmosConnection class
    }
    

    的代码为 CosmosConnection
    @Configuration
    @ComponentScan
    public class CosmosConnection {
        @Value("${cosmos.connectionuri}") private String uri;
        @Value("${cosmos.primarykey}") private String primarykey;
    
    public String connectToDB() throws DocumentClientException, IOException, ParseException {
        System.out.println("URI is " + uri); //getting this as null
    

    我需要做些什么更改才能从bootstrap.yml中选择值?

    最佳答案

    带有spring框架的javax.annotation包中的一个名为PostConstruct的注释可用于解决该问题。如源代码中所述:

    The PostConstruct annotation is used on a method that needs to be executed
     after dependency injection is done to perform any initialization
    

    下面的代码是一个示例:

    @Configuration
    public class ComosConfig {
      @Value("${cosmos.connectionuri}") private String uri;
      @Value("${cosmos.primarykey}") private String primarykey;
    
      //get and set methods here
    }
    

    public class CosmosConnection {
      private String uri;
      private String primaryKey;
    
      public CosmosConnection(String uri, String primaryKey) {
        this.uri = uri;
        this.primaryKey = primaryKey;
      }
    
      public String connectToDB() {
        //do something here
      }
    }
    

    @Component
    public class SupplierGetResponseFeed {
      private static CosmosConnection cosmos;
      private CosmosConfig config;
    
      public SupplierGetResponseFeed(CosmosConfig config) {
        this.config = config;
      }
    
      @PostConstruct
      public void init() {
        String uri = config.getUri();
        String primaryKey = config.getprimaryKey();
        cosmos = new cosmos(uri, primaryKey);
      }
    
      public static SupplierResponseDataEntity prepareSupplierAzureData() {
        cosmos.connectToDB(); //calling the method of CosmosConnection class
      }
    }
    

    毕竟,鉴于代码分析实用程序不建议从实例方法写入静态,因此建议您将init方法与抑制警告注释一起使用以消除警告。

    07-24 09:15