简体   繁体   English

Spring Boot 属性自动装配不起作用

[英]Spring boot property autowiring not working

I have a Spring boot 2.3.3.RELEASE project.我有一个 Spring Boot 2.3.3.RELEASE项目。

Main Application class,主要应用类,

    @SpringBootApplication()
    public class TestApplication {
           ...
    }
    
    @ConfigurationProperties(prefix = "test")
    public class TestProperties {
      ...
    }
    
    @Configuration
    @EnableConfigurationProperties({TestProperties.class})
    public class TestConfiguration {
    
    }

@Service
public class AmazonEmailService {

    private final AmazonSimpleEmailService client;
    
    @Autowired
    private TestProperties props;

    public AmazonEmailService() {
      props.getEmail(); // Here props is null ...
    }

}

Here, TestProperties autowiring is null in AmazonEmailService .在这里, TestProperties自动装配在AmazonEmailService Not sure what is missing.不确定缺少什么。

Other Autowiring works in other classes.其他自动装配适用于其他课程。

Can you use @Autowired on the constructor instead?您可以在构造函数上使用@Autowired吗?

private TestProperies props;    

@Autowired
public AmazonEmailService(TestProperties props){
   this.props=props; 
   props.getEmail(); //Ok now.
}

This is because using @Autowired on property, Spring inject the value AFTER object create.这是因为在@Autowired上使用@ @Autowired ,Spring 会在创建对象注入值。 But in your case, you try to use the props inside the contructor.但是在您的情况下,您尝试使用构造函数内部的道具。 At that moment, it's still null那一刻,它还为空

在 TestProperties 类上添加 @Component 注解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM