如何从静态实例中获取bootstrap.yml文件的值

时间:2018-04-09 16:16:32

标签: java spring spring-boot autowired

  • 我有一个课程 CosmosConnection SupplierGetResponseFeed
  • 我从 SupplierGetResponseFeed
  • 中调用 CosmosConnection 的方法
  • SupplierGetResponseFeed 的方法,我称之为 CosmosConnection 方法是静态的
  • 示例:public static SupplierResponseDataEntity prepareSupplierAzureData(Map<String, Object> row, String[] columnNames) {
  • 因此,当我在 SupplierGetResponseFeed 中创建 CosmosConnection 的对象时,我无法使用@Autowired作为我无法从引导程序中选择值的原因 CosmosConnection
  • 中的.yml文件
  • 虽然我在 SupplierGetResponseFeed 中使用@Autowired创建了对象,但我无法从bootstrap中选择值

    @Autowired     静态CosmosConnection宇宙;

以下是 SupplierGetResponseFeed

的代码
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中选择值需要做些什么改变?

1 个答案:

答案 0 :(得分:0)

带有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方法一起使用的抑制警告注释来消除警告。