我的application.yaml:
spring:
profiles: test
mysvc:
server: https://myserver.com
user: john123
passwd: pass123!
我的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());
}
在Application类中,没问题,我可以访问mySvcProps中的方法并获取值。但是在MySvc类中,mySvcProps为空。
所有类共享相同的基本程序包名称,为什么自动装配在MySvc类中不起作用?
我只能按照以下文档使其工作:https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external -config-yaml
使用从调用方接受自动装配的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());
}
}
不知道为什么会这样工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句