public static SupplierResponseDataEntity prepareSupplierAzureData(Map<String, Object> row, String[] columnNames) {
@Autowired
。CosmosConnection @自动连线
静态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方法与抑制警告注释一起使用以消除警告。