通过SpringBoot配置文件配置API主机

时间:2018-12-27 16:27:14

标签: java spring configuration

我正在为项目使用SpringBoot,Java和Gradle。 我的API连接到通过spring属性配置的数据库,但也依赖于外部API Rest来获取某些数据。

我的问题是是否可以使用spring属性配置外部API主机和密码? 我应该使用哪些属性? 有没有创建自定义属性的方法?

ObjectMapper.readValue

2 个答案:

答案 0 :(得分:1)

是的。最简单的方法是在application.yml中定义您喜欢的任何属性名称:

api:
 url: http://api.com/blablba/
 password: fooPassword

然后使用@Value将这些值注入API客户端bean:

@Component
public class ApiClient {

   @Value("${api.url}")
   private String url;

   @Value("${api.password}")
   private String password;

}

答案 1 :(得分:1)

您可以安全地采用以下方法,在yml文件中配置所有秘密以及外部API端点。如果要隐藏秘密,请进一步使用Spring Vault来存储和撤消秘密。 https://projects.spring.io/spring-vault/

security:
  basic:
    enabled: ${env.security.basic.enabled:false}
management:
  security:
    enabled: ${env.management.security.enabled:false}


apiUsername: apiUser
apiPassword: apiPassword
apiUrl: http://external-rest-api/RESTAdapter
dbUsername: dbUsername
dbPassword: dbPassword
dbServerUrl: jdbc:jtds:sqlserver://localhost:1433;
dbDriverClass: net.sourceforge.jtds.jdbc.Driver
dbServerDialect: org.hibernate.dialect.SQLServerDialect
dbName: databaseName=dbName;

---
spring:
  profiles: Prod
dbDriverClass: net.sourceforge.jtds.jdbc.Driver
dbServerDialect: org.hibernate.dialect.SQLServerDialect
dbName: databaseName=prodDBName;

写一个服务启动器,通过从yml文件中获取属性来启动服务。

@Configuration
@EnableJpaRepositories("com.dao")
public class ServiceConfig {

    /**
     * The meta data bean consisting of properties read from the yaml
     * configuration file.
     */


    @Value("${apiUsername}")
    String apiUsername;

    @Value("${apiPassword}")
    String apiPassword;

    @Value("${apiUrl}")
    String apiUrl;


    @Value("${dbUsername}")
    String dbUsername;

    @Value("${dbPassword}")
    String dbPassword;

    @Value("${dbServerUrl}")
    String dbServerUrl;


    @Value("${dbDriverClass}")
    String dbDriverClass;

    @Value("${dbServerDialect}")
    String dbServerDialect;

    @Value("${dbName}")
    String dbName;




    /**
     * Creates and returns a bean of RestClientSapUtil.
     * 
     * @return RestClientApiUtil bean
     */
    @Bean(name = "restClientApiUtil")
    public RestClientApiUtil getRestClientApiUtil() {
        return new RestClientApiUtil(apiUsername, apiPassword, apiUrl);
    }

    @Bean(name = "datasource")
    public DriverManagerDataSource getDriverManagerDataSource() {
        DriverManagerDataSource driverManagerDataSource =
                new DriverManagerDataSource();
        driverManagerDataSource.setUsername(dbUsername);
        driverManagerDataSource.setPassword(dbPassword);
        driverManagerDataSource.setUrl(dbServerUrl + dbName);
        driverManagerDataSource.setDriverClassName(dbDriverClass);
        return driverManagerDataSource;
    }

    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean getLocalContainerEntityManagerFactoryBean() {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
                new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter jpaVendorAdapter =
                new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setShowSql(true);
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setDatabasePlatform(dbServerDialect);
        localContainerEntityManagerFactoryBean
                .setJpaVendorAdapter(jpaVendorAdapter);
        localContainerEntityManagerFactoryBean
                .setDataSource(getDriverManagerDataSource());
        localContainerEntityManagerFactoryBean
                .setPackagesToScan("com.model");
        return localContainerEntityManagerFactoryBean;
    }

    @Bean(name = "transactionManager")
    public JpaTransactionManager getJpaTransactionManager(
            EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }   

}

最后,您可以构建一个与外部API接口通信的实用程序类,您可以在下面考虑类似的情况。

/**
 * Provides methods for making requests to the API interface.
 * 
 *
 */
public class RestClientApiUtil {

    public RestClientApiUtil() {
    }


    private String apiUsername;

    /**
     * The password for accessing the external API interface.
     */
    private String apiPassword;

    /**
     * The base URL for accessing the external API  interface.
     */
    private String apiUrl;


    public RestClientApiUtil(String apiUsername, 
            String apiPassword, String apiUrl) {
        this.apiUsername = apiUsername;
        this.apiPassword = apiPassword;
        this.apiUrl = apiUrl;
    }

    /**
     * Makes a call to the external API interface and returns the response received.
     * @param requestData the request data to attach in the request body
     * @param endpoint the specific endpoint to make a request to
     * @param clazz the class in which the response is expected
     * @return Object
     * @throws Exception
     */
    public <T> T callService(Object requestData, String endpoint, Class<T> clazz)
            throws TechnicalException {


        RestTemplate restTemplate = null;
        ResponseEntity<?> responseEntity = null;
        String webServiceUrl = "";
        HttpEntity<Object> requestBody = null;
        try {
            webServiceUrl = formServiceUrl(this.apiUrl, endpoint);
            requestBody = createRequestBody(requestData);
            restTemplate = new RestTemplate();
            responseEntity = restTemplate.exchange(webServiceUrl, HttpMethod.POST, requestBody, clazz);
            return clazz.cast(responseEntity.getBody());
        } catch (Exception e) {
            throw new Exception(e);
        } 
    }

}

如果您还有其他疑问,请告诉我。 干杯!