- 我有一个类CosmosConnection和SupplierGetResponseFeed
- 我正在从SupplierGetResponseFeed调用CosmosConnection的方法
- 我从中调用CosmosConnection方法的SupplierGetResponseFeed方法是静态的
- 例 :
public static SupplierResponseDataEntity prepareSupplierAzureData(Map<String, Object> row, String[] columnNames) {
- 因此,当我在SupplierGetResponseFeed中创建CosmosConnection的对象时,我不能使用
@Autowired
作为我无法从CosmosConnection中的bootstrap.yml文件中选择值的原因 -
虽然我在SupplierGetResponseFeed中使用@Autowired创建对象,但我无法从引导程序中选取值
@Autowired 静态宇宙连接宇宙;
以下是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
}
的代码是宇宙连接
@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 方法一起使用抑制警告注释来消除警告。