[英]Bean injection failing in Library
我创建了一个库,在其中创建了一些bean。 以下是我正在创建一些bean的文件:
@Configuration
public class StorageBindings {
@Value("${storageAccountName}")
private String storageAccountName;
@Value("${storageAccountKey}")
private String storageAccountKey;
@Bean(name = "cloudBlobClient")
public CloudBlobClient getCloudBlobClientUsingCredentials() throws URISyntaxException {
return new CloudBlobClient();
}
@Bean(name = "storageCredentialsToken")
public StorageCredentialsToken getStorageCredentialsToken() throws IOException {
return new StorageCredentialsToken();
}
@Bean(name = "msiTokenGenerator")
public MSITokenGenerator getMSITokenGenerator() {
return new MSITokenGenerator();
}
}
然后,我创建了该类,将其用作入口点以进行进一步的操作
public class StorageClient {
@Autowired
private CloudBlobClient cloudBlobClient;
@Autowired
private MSITokenGenerator msiTokenGenerator;
@Value("${storageAccountName}")
private String storageAccountName;
@Value("${storageAccountKey}")
private String storageAccountKey;
}
我用上述文件创建了jar,并将其包含在我们的主项目中,在其中创建了StorageClient的bean,如下所示:
@Bean(name = {"storageClient"})
public StorageClient getStorageClient() {
LOG.debug("I am inside storage class");
StorageClient ac = null;
try {
ac = new StorageClient();
return ac;
}
但是执行后,我发现在StorageClient实例ac中没有注入以下变量,甚至没有反映环境属性,并且所有这些都为null:
//beans NOT Injecting
ac.cloudBlobClient=null;
ac.msiTokenGenerator=null;
//env variables
ac.storageAccountName=null;
ac.storageAccountKey=null;
我是否想念一些东西,因为我越来越空了。 实例化bean的顺序还可以。 我检查了。 因此,首先创建了StorageBindings的bean。
执行此操作时:
ac = new StorageClient();
您失去了spring的上下文,因为您是根据该上下文创建一个新实例。 CloudBlobClient
, MSITokenGenerator
和变量storageAccountName
, storageAccountKey
内的bean不会被注入。
您可以使用@Component
注释StorageClient
。
因此,由于将其打包为jar,因此在主项目中,必须确保@ComponentScan
包含StorageClient
所在的路径。
然后,您可以执行以下操作:
@Autowired
private StorageClient storageClient;
在您的主要项目中。
如果要在@Bean
注释的方法中创建对象, @Bean
自动装配不会在其中注入@Bean
您只是在自己创建它。 因此,您必须@Autowire
,即在Configuration
类中的字段上并使用setter / constructor进行设置。 即:
@Autowired
private CloudBlobClient cloudBlobClient;
@Autowired
private MSITokenGenerator msiTokenGenerator;
@Bean(name = {"storageClient"})
public StorageClient getStorageClient() {
LOG.debug("I am inside storage class");
StorageClient ac = null;
try {
ac = new StorageClient();
ac.setCloudBlobClient(cloudBlobClient);
ac.setMsiTokenGenerator(msiTokenGenerator);
return ac;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.