英文:
Spring boot property autowiring not working
问题
我有一个Spring Boot 2.3.3.RELEASE
项目。
主应用程序类,
@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(); // 这里 props 是 null ...
}
}
在这里,AmazonEmailService
中的 TestProperties
自动装配为 null。不确定缺少了什么。
其他类中的自动装配是正常的。
英文:
I have a Spring boot 2.3.3.RELEASE
project.
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
. Not sure what is missing.
Other Autowiring works in other classes.
答案1
得分: 3
能否在构造函数上使用 @Autowired
?
private TestProperies props;
@Autowired
public AmazonEmailService(TestProperties props){
this.props=props;
props.getEmail(); //现在可以了。
}
这是因为在属性上使用 @Autowired
时,Spring 会在对象创建之后注入该值。但在您的情况下,您尝试在构造函数内部使用 props。在那时,它仍然为 null。
英文:
Can you use @Autowired
on the constructor instead?
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. But in your case, you try to use the props inside the contructor. At that moment, it's still null
答案2
得分: 0
在TestProperties类上添加@Component注解。
英文:
Add @Component annotation on TestProperties class
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论