Spring Boot自动装配属性问题

问题描述

我正在玩Spring-boot自动接线,以了解更多有关它的知识,但我并不了解。在下面的代码中,启动类的自动装配有效,但更高级别的类的无效。结果是“ SpringApplication.run”将正确打印出属性,而“ demo.print()”则不会。有人可以帮助我了解为什么以及如何使其工作吗?

package demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@SpringBootApplication
@EnableConfigurationProperties(EmailProperties.class)
public class DemoApplication {


@Autowired
private EmailProperties properties;

public static void main(String[] args) {

    SpringApplication.run(DemoApplication.class,args);
    
    DemoApplication demo = new DemoApplication();
    demo.print();
    
}

private void print() {
    System.out.println("Partner support: " + this.properties.getPartnerSupport());
}


DemoApplication(){
}


@Service
static class Startup implements CommandLineRunner {

    @Autowired
    private EmailProperties properties;

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("-----------------------------------------");
        System.out.println("Client support: " + this.properties.getClientSupport());
        System.out.println("Partner support: " + this.properties.getPartnerSupport());
        System.out.println("No reply to: " + this.properties.getnoreplyTo());
        System.out.println("Support reply to: " + this.properties.getSupportReplyTo());
        System.out.println("OpS notification: " + this.properties.getopsNotification());
        System.out.println("-----------------------------------------");
    }
}

}

如果需要,我可以发布演示代码的其他部分。谢谢。

解决方法

当您调用SpringApplication.run(DemoApplication.class,args);时,Spring将创建自己的DemoApplication实例,看到它具有@Autowired个成员并自动装配它们。这就是通常所说的托管bean

您的@Service类也将被实例化并自动连线,由于它也是CommandLineRunner,因此Spring会在自动连线后调用run()方法 豆。

另一方面,当您调用DemoApplication demo = new DemoApplication();时,您将创建自己的DemoApplication实例,该实例不受的管理。结果,properties字段中的任何内容都不会自动接线,而该字段保留为null

为了更好地理解Spring的工作原理,尤其是托管实例与非托管实例之间的关系,我强烈建议您阅读《 Spring Framework Reference,The IoC Container》的第一章。