代码之家  ›  专栏  ›  技术社区  ›  Michael

未调用Spring注释导入配置

  •  0
  • Michael  · 技术社区  · 6 年前

    我试图创建一个使用Spring注释导入配置的应用程序。对于这个问题,我把范围缩小到两个文件。启动类:

    package core;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    
    @Slf4j
    @Configuration
    @Import(ConfigSettings.class)
    public class Startup {
        public static void main (String args[]) {
        log.info("main class");
        }
    }
    

    包装核心;

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Slf4j
    @Configuration
    @ComponentScan({"connections", "filter"})
    @PropertySource({"classpath:config/${env.config:dev}.application.properties"})
    public class ConfigSettings {
    
        public ConfigSettings() {
        log.info("Constructor ConfigSettings");
        }
    }
    

    我希望结果是:

    [INFO]Constructor ConfigSettings
    [INFO]main class
    

    但它只显示主舱。看起来配置设置的构造函数根本没有被调用。我希望它调用它是因为import注释。

    有谁能解释出什么事了吗?提前谢谢你!

    0 回复  |  直到 6 年前
        1
  •  2
  •   Shadowheim    6 年前

    最好的办法是让config类返回包含您的值的config对象。一般来说,我不打算添加一个包罗万象的配置对象,而是为每个组件(数据库、控制器等)添加一个配置文件。

    然后可以将配置好的对象作为bean返回,并让spring注入它。如果我要为RestTemplate创建一个配置文件(作为一个简单的例子):

    @Service
    public class RestClientConfig {
    
        @Value("${your.config.value}")
        private String yourValue;
    
    
        private final RestTemplate restTemplate = new RestTemplate();
    
        @Bean
        public RestTemplate restTemplate() {
          // Configure it, using your imported values
          // ...
    
          return restTemplate;
       }
    }
    

    然而 main