簡體   English   中英

為什么注入bean后得到null個值?

[英]Why do I get null values after injecting bean?

當我嘗試在Operation.class中注入packagePropertiesList Bean 時,我從屬性文件中獲取值。 但是當我使用operation.removeStudentFromList()時,我只得到 null 個值。 你看到這里有什么問題嗎?

注入 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;
    }
}

應用程序.properties

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()時為 output

您正在 Spring Boot(使用new AnnotationConfigApplicationContext()已經創建的那個旁邊創建一個額外的 ApplicationContext 。刪除它並使用現有上下文獲取一個 bean,或者更確切地說,如果您想運行,請查看ApplicationRunner接口應用程序啟動后自動編碼。

整個屬性處理僅適用於由 Spring Boot 創建和管理的應用程序上下文,不適用於您自己創建的應用程序上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM