2017-05-05 15 views
0

我有这样定义的属性的类:像这样如何将@ConfigurationProperties自动装配到@Configuration中?

@Validated 
@ConfigurationProperties(prefix = "plugin.httpclient") 
public class HttpClientProperties { 
    ... 
} 

和一个配置类:

@Configuration 
@EnableScheduling 
public class HttpClientConfiguration { 

    private final HttpClientProperties httpClientProperties; 

    @Autowired 
    public HttpClientConfiguration(HttpClientProperties httpClientProperties) { 
     this.httpClientProperties = httpClientProperties; 
    } 

    ... 
} 

当开始我的春天启动的应用程序,我得到

Parameter 0 of constructor in x.y.z.config.HttpClientConfiguration required a bean of type 'x.y.z.config.HttpClientProperties' that could not be found. 

这不是一个有效的用例,还是我必须声明一些依赖关系?

回答

1

这是一个有效的用例,但是,你的HttpClientProperties没有捡到,因为他们没有通过该组件扫描仪扫描。你可以注解你HttpClientProperties@Component

@Validated 
@Component // This is a possibility, though not recommended 
@ConfigurationProperties(prefix = "plugin.httpclient") 
public class HttpClientProperties { 
    // ... 
} 

但是,这样做(如由Stephane Nicoll提及)的推荐的方法是,通过使用Spring的配置类的注释,例如:

@EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way 
@EnableScheduling 
public class HttpClientConfiguration { 
    // ... 
} 

这也是在Spring boot docs说明。

+0

还有一件事困扰我虽然。我有另一个ConfigurationProperties类,它也没有注释为组件,但是它自动装配到组件中。这样可行。怎么来的? – Daniel

+0

@Daniel那么一定还有其他的区别。无论是在配置类(用@ Bean注释)中创建的bean,还是在配置属性类上都有另一个允许组件扫描的注释。 – g00glen00b

+1

其实我们真的不建议使用'@ Component',这在DOC已经描述:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features- external-config-typesafe-configuration-properties –

相关问题