我有一个 application.yml 文件,其中包含如下对象列表:
outlook:
mailboxes:
- id: m1
name: mailbox1
- id: m2
name: mailbox2
我创建了一个名为MailBoxProperties的 spring 配置类,以便在 bean 中具有这些属性,如下所示:
邮箱属性.java
@ConfigurationProperties(prefix = "outlook")
@Configuration
public class MailBoxProperties {
private List<MailBox> mailboxes;
public MailBoxProperties() {
}
public MailBoxProperties(List<MailBox> mailboxes) {
this.mailboxes = mailboxes;
}
public void setMailBoxes(List<MailBox> mailboxes) {
this.mailboxes = mailboxes;
}
public List<MailBox> getMailBoxes() {
return mailboxes;
}
public static class MailBox {
public String getName() {
return this.name;
}
public String getId() {
return this.id;
}
private String id, name;
public MailBox() {
}
public MailBox(String id, String name) {
this.id = id;
this.name = name;
}
}
}
我想将上面的配置 bean 注入到另一个配置类中,如下所示:
OutlookConnectionManager.java
@Configuration
@EnableConfigurationProperties
public class OutlookConnectionManager{
@Autowired
private MailBoxProperties mailBoxProperties;
private List<String> names;
@Bean
public OutlookConnectionManager getOutlookConnectionManager() {
OutlookConnectionManager outlookConnectionManager = new OutlookConnectionManager();
outlookConnectionManager.getMailBoxProperties();
return outlookConnectionManager;
}
public void getMailBoxProperties() {
names = new ArrayList<String> ();
for(MailBox mail: mailBoxProperties.getMailBoxes()) {
this.names.add(mail.getName());
}
}
}
但是,MailBoxProperties 始终为空,并在从 getMailBoxProperties 调用 mailBoxProperties.getMailBoxes() 时引发空指针异常。
(我试过给@Configuration @EnableConfigurationProperties(MailBoxProperties.class)。它抛出一个异常,说明创建了2个bean。一个带有实际路径,另一个带有null)。我试过@Import(){MailBoxProperties.class}。
但是,注入在我的主应用程序类中完美运行,如下所示:它获取 bean 并正确打印邮箱名称。
邮件应用程序.java
@SpringBootApplication
public class MailApplication {
public static void main(String[] args) {
ApplicationContext context = new SpringApplicationBuilder(MailApplication.class).run(args);
MailBoxProperties props = context.getBean(MailBoxProperties.class);
props. getMailBoxes()
.forEach(cc -> System.out.println(cc.getName()));
}
}
我是否缺少 OutlookConnectionManager.java 中的任何配置?请帮忙。
注意: 我使用的是 Spring boot 1.5.7.RELEASE
谢谢你。