需要在bean初始化期间注入属性

时间:2018-03-19 13:19:23

标签: java spring autowired

我有一个使用REST的应用程序,我想将我的API令牌参数化为RestTemplate。我试图自动装载包含令牌的bean,但是在创建RestTemplate时bean仍然为null。我想我可以用@PostConstruct以某种方式做到这一点,但我无法提出代码。所以我有这个:

package com.company;
...
import com.company.api.dashboard.config.Credentials;

@SpringBootApplication
public class Main implements CommandLineRunner {
    @Autowired
    DashboardClient client;

    @Autowired
    Credentials credentials;

    public static void main(String... args) throws Exception {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public RestTemplate restTemplateAS(RestTemplateBuilder builder) {
         // here is where I try to use the autowired Credentials class
        return builder.additionalInterceptors(new ASRequestHeaderInterceptor("Authorization", "Bearer " + credentials.getApiToken()), 
                                              new ASRequestHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON.toString()),
                                              new LoggingRequestInterceptor())
                .messageConverters(new MappingJackson2HttpMessageConverter())
                .requestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
                .build();
    }
    ...
}

这是Credentials bean:

package com.company.api.dashboard.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties("credentials")
public class Credentials {
    private String oauthUser;

    private String oauthPassword;

    private String apiToken;

    public String getOauthUser() {
        return oauthUser;
    }

    public void setOauthUser(String oauthUser) {
        this.oauthUser = oauthUser;
    }

    public String getOauthPassword() {
        return oauthPassword;
    }

    public void setOauthPassword(String oauthPassword) {
        this.oauthPassword = oauthPassword;
    }

    public String getApiToken() {
        return apiToken;
    }

    public void setApiToken(String apiToken) {
        this.apiToken = apiToken;
    }
}

如果我无法自动发送apiToken属性,我还能从application.yml获取它吗?

1 个答案:

答案 0 :(得分:0)

使用@EnableConfigurationProperties(Credentials.class)为要处理的属性注释主类。并从Credetials类中删除@Configuration