Spring Boot读数yml null

nkhmeac6  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(372)

我试图从yml文件中获取值
这是我的申请表-

inbox:  
  inboxlist:
    -INBOX
    -TEST

以下是数据存储在-inboxconfig.java中的位置

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import lombok.Data;

@Data
@Component
@ConfigurationProperties(prefix = "inbox")
public class InboxConfig {
    private static final Logger logger = LoggerFactory.getLogger(InboxConfig.class);

    private List<String> inboxlist;

(注意我使用lombok,所以没有getter)
这就是我所说的

@EnableConfigurationProperties
public class SFEmailServiceHandler {
    private static final Logger logger = LoggerFactory.getLogger(SFEmailServiceHandler.class);

    ArrayList<String> mailTo = new ArrayList<String>();

    @Autowired
    protected InboxConfig inboxConfig;
    List<String> Inboxlist = inboxConfig.getInboxlist();

但我明白了 Cannot invoke "*myorg*.InboxConfig.getInboxlist()" because "this.inboxConfig" is null 我错过什么了吗?我对springboot还不熟悉,我真的不知道自动连线是怎么工作的。

ibps3vxo

ibps3vxo1#

使用@postconstruct
自动连接(注入)后将调用此方法。

@EnableConfigurationProperties
public class SFEmailServiceHandler {
    private static final Logger logger = LoggerFactory.getLogger(SFEmailServiceHandler.class);

    ArrayList<String> mailTo;

    @Autowired
    protected InboxConfig inboxConfig;
    List<String> Inboxlist;

    @PostConstruct
    private void postConstruct() {
        mailTo = new ArrayList<String>();
        Inboxlist = inboxConfig.getInboxlist();
    }
}
ix0qys7i

ix0qys7i2#

在获取列表值之前,还必须将类注册为“springbean”。
(示例)

inbox:
  inboxlist:
    - INBOX  # Add space... 
    - TEST
@Slf4j
@Component
@EnableConfigurationProperties(InboxConfig.class)
public class SFEmailServiceHandler {

    @Autowired
    protected InboxConfig inboxConfig;
    List<String> inboxlist;

    @PostConstruct
    private void init() {

        this.inboxlist = inboxConfig.getInboxlist();
        log.info("inboxlist : {} ", inboxlist);
    }
}

相关问题