Java 通过SpringBoot配置文件配置API主机
我在我的项目中使用SpringBoot、Java和Gradle。 我的API连接到通过spring属性配置的数据库,但也依赖外部API Rest进行一些数据检索 我的问题是,有没有一种方法可以使用spring属性配置外部API主机和密码? 我应该使用哪些属性? 有没有办法创建自定义属性Java 通过SpringBoot配置文件配置API主机,java,spring,configuration,Java,Spring,Configuration,我在我的项目中使用SpringBoot、Java和Gradle。 我的API连接到通过spring属性配置的数据库,但也依赖外部API Rest进行一些数据检索 我的问题是,有没有一种方法可以使用spring属性配置外部API主机和密码? 我应该使用哪些属性? 有没有办法创建自定义属性 ## application.yml --- spring: profiles: dev datasource: platform: postgres url: jdbc:postgre
## application.yml
---
spring:
profiles: dev
datasource:
platform: postgres
url:
jdbc:postgresql://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}
username: ${DATABASE_USER}
password: ${DATABASE_PASSWORD}
driverClassName: org.postgresql.Driver
initialize: true
liquibase:
change-log: classpath:db/changelog-master.xml
是的。最简单的方法就是在
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;
}
是的。最简单的方法就是在
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;
}
您可以安全地采用以下方法,在
yml
文件中配置所有机密以及外部API端点。如果您想进一步隐藏机密,请使用用于存储和撤销机密的Spring Vault
。
编写一个服务启动程序,通过从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);
}
}
}
/**
*提供向API接口发出请求的方法。
*
*
*/
公共类RestClientApiUtil{
公共RestClientApiUtil(){
}
私有字符串;
/**
*用于访问外部API接口的密码。
*/
私有字符串密码;
/**
*用于访问外部API接口的基本URL。
*/
私有字符串apirl;
公共RestClientApiUtil(字符串apiUsername,
字符串apiPassword,字符串apiUrl){
this.apiUsername=apiUsername;
this.apiPassword=apiPassword;
this.apiUrl=apiUrl;
}
/**
*调用外部API接口并返回收到的响应。
*@param requestData要附加到请求正文中的请求数据
*@param endpoint要向其发出请求的特定端点
*@param clazz预期响应所在的类
*@返回对象
*@抛出异常
*/
公共调用服务(对象请求数据、字符串端点、类clazz)
感觉异常{
RestTemplate RestTemplate=null;
ResponseEntity ResponseEntity=null;
字符串webServiceUrl=“”;
HttpEntity requestBody=null;
试一试{
webServiceUrl=formServiceUrl(this.apiUrl,端点);
requestBody=createRequestBody(requestData);
restTemplate=新的restTemplate();
responseEntity=restTemplate.exchange(webServiceUrl、HttpMethod.POST、requestBody、clazz);
返回clazz.cast(responseEntity.getBody());
}捕获(例外e){
抛出新异常(e);
}
}
}
我希望这个答案有点道理,如果你有任何进一步的问题,请告诉我。
干杯 您可以安全地采用以下方法,在
yml
文件中配置所有机密以及外部API端点。如果您想进一步隐藏机密,请使用用于存储和撤销机密的Spring Vault
。
编写一个服务启动程序,通过从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);
}
}
}
/**
*提供向API接口发出请求的方法。
*
*
*/
公共类RestClientApiUtil{
公共RestClientApiUtil(){
}
私有字符串;
/**
*用于访问外部API接口的密码。
*/
私有字符串密码;
/**
*用于访问外部API接口的基本URL。
*/
私有字符串apirl;
公共RestClientApiUtil(字符串apiUsername,
字符串apiPassword,字符串apiUrl){
this.apiUsername=apiUsername;
this.apiPassword=apiPassword;
this.apiUrl=apiUrl;
}
/**
*调用外部API接口并返回收到的响应。
*@param requestData要附加到请求正文中的请求数据
*@param endpoint要向其发出请求的特定端点
*@param clazz预期响应所在的类
*@返回对象
*@抛出异常
*/
公共调用服务(对象请求数据、字符串端点、类clazz)
感觉异常{
RestTemplate RestTemplate=null;
ResponseEntity ResponseEntity=null;
字符串webServiceUrl=“”;
HttpEntity requestBody=null;
试一试{
webServiceUrl=formServiceUrl(this.apiUrl,端点);
requestBody=createRequestBody(requestData);
restTemplate=新的restTemplate();
responseEntity=restTemplate.exchange(webServiceUrl、HttpMethod.POST、requestBody、clazz);
返回clazz.cast(responseEntity.getBody());
}捕获(例外e){
抛出新异常(e);
}
}
}
我希望这个答案有点道理,如果你有任何进一步的问题,请告诉我。
干杯