當我嘗試將packagePropertiesListBean 注入時Operation.class,我從屬性檔案中獲取值。但是當我使用時operation.removeStudentFromList(),我只得到空值。你看到這里有什么問題嗎?
注入 bean 時的值
@SpringBootApplication
public class LearningCenterApplication {
public static void main(String[] args) {
SpringApplication.run(LearningCenterApplication.class, args);
ApplicationContext context =
new AnnotationConfigApplicationContext(Config.class, Operations.class, PackageProperties.class);
Operations operations = context.getBean(Operations.class);
operations.removeStudentFromList();
}
@Bean
List<PackageProperties> packagePropertiesList(List<PackageProperties> packageProperties) {
System.out.println(packageProperties);
return packageProperties;
}
@Bean
@ConfigurationProperties(prefix = "remove")
public PackageProperties removeMethod() {
return new PackageProperties();
}
@Bean
@ConfigurationProperties(prefix = "add")
public PackageProperties addMethod() {
return new PackageProperties();
}
}
@Component
public class Operations {
private List<PackageProperties> packagePropertiesList;
@Autowired
public Operations(List<PackageProperties> packagePropertiesList) {
this.packagePropertiesList = packagePropertiesList;
}
public void removeStudentFromList() {
System.out.println(packagePropertiesList);
}
}
public class PackageProperties {
private String packageName;
private String className;
private String methodName;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public String toString() {
return packageName "." className "." methodName;
}
}
應用程式屬性
remove.packageName = org.epam.operations
remove.className = Operations
remove.methodName = removeStudentFromList()
add.packageName = org.epam.operations
add.className = Operations
add.methodName = addStudent()
[null.null.null]—operations.removeStudentFromList()呼叫時輸出
uj5u.com熱心網友回復:
您正在 Spring Boot 已經創建的 ApplicationContext 旁邊創建一個附加 ApplicationContext (使用new AnnotationConfigApplicationContext(). 洗掉它并使用現有背景關系獲取 bean,或者ApplicationRunner如果您想在應用程式之后自動運行代碼,請查看介面已經開始。
整個屬性處理僅適用于由 Spring Boot 創建和管理的應用程式背景關系,而不適用于您自己創建的應用程式背景關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439934.html
