Spring boot 自定义yaml属性在服务类中不可用

Spring boot 自定义yaml属性在服务类中不可用,spring-boot,Spring Boot,My application.yaml: spring: profiles: test mysvc: server: https://myserver.com user: john123 passwd: pass123! My application.java类: @SpringBootApplication @EnableConfigurationProperties public class Application implements CommandLineRu

My application.yaml:

spring:
  profiles: test
mysvc:  
   server: https://myserver.com
   user: john123
   passwd: pass123!
My application.java类:

@SpringBootApplication
@EnableConfigurationProperties
public class Application implements CommandLineRunner {

    @Autowired
    MySvcProps mySvcProps;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
      @Override
        public void run(String... args) {
            System.out.println(mySvcProps.getServer());
        }
}
我的属性类:

@Component
@ConfigurationProperties(prefix="mysvc")
public class MySvcProps{

    private String server;
    private String user;
    private String passwd;

    // setters/getters
}
我的服务级别:

@Service
public class MySvc {
        @Autowired
        MySvcProps mySvcProps;

public void printServer() {
    System.out.println(mySvcProps.getServer());
}
在应用程序类中,没问题,我可以访问mySvcProps中的方法并获取值。但在MySvc类中,mySvcProps为null


所有类都共享相同的基本包名称,为什么autowire不能在MySvc类中工作?

我只能根据以下文档使其工作:

使用接受调用者自动连接的mySvcProps的构造函数更新我的服务:

    @Service
    public class MySvc {

    private final MySvcProps mySvcProps;

        @Autowired
        public MySvc (MySvcProps mySvcProps) {
            this.mySvcProps= mySvcProps;
        }

        public void printServer() {
            System.out.println(mySvcProps.getServer());
        }
    }
不知道为什么会这样。

你试过了吗