【问题标题】:How to make encapsulation for configuration java如何对配置java进行封装
【发布时间】:2026-01-15 14:30:01
【问题描述】:

我已经从 yml 读取了我的配置,并且我还为我的项目添加了配置 java 文件,但不知何故我无法封装它们,我有点困惑如何将它们作为私有字段;

下面是我的yml;

conf-listener:
  listenConfForInfoEvent:
    second: 19000
  listenConfForWarnEvent:
    second: 29000
  listenConfForErrorEvent:
    second: 39000

下面是我的班级;

@Configuration
@ConfigurationProperties(prefix = "conf-listener")
public class ConfEventListenerConfiguration {

    ListenConfEvent listenConfForInfoEvent = new ListenConfEvent ();
    ListenConfEvent listenConfForWarnEvent = new ListenConfEvent ();
    ListenConfEvent listenConfForErrorEvent = new ListenConfEvent ();

   // public getter and setters

    public static class ListenConfEvent {
        int hour = 0;
        int minute = 0;
        int second = 0;
        int milliSecond = 0;

      // public getters and setters

不知何故我无法封装它们,任何帮助

【问题讨论】:

  • setter 和 getter 名称必须与属性中的名称匹配。您确定它们的名称正确吗?也不需要那些默认值
  • 另外:不应该是@Component 而不是@Configuration
  • 是依赖 org.springframework.bootspring-boot-configuration-processortrue依赖>

标签: java spring spring-boot rest


【解决方案1】:

您不必通过new 创建对象,让 spring 为您完成。请在下面尝试并查看。如果这不起作用,那么您需要检查您的 .yaml 文件是否格式正确且没有间距问题。

@Configuration
@ConfigurationProperties(prefix = "conf-listener")
public class ConfEventListenerConfiguration {

    private ListenConfEvent listenConfForInfoEvent;
    private ListenConfEvent listenConfForWarnEvent;
    private ListenConfEvent listenConfForErrorEvent;

   // public getter and setters

    public static class ListenConfEvent {
        private int second;
       // public getter and setters
     }
}

【讨论】:

  • 谢谢你的这部分还有其他方法吗?公共静态类 ListenConfEvent { 私有 int 秒; // 公共 getter 和 setter }