it is pretty long time that I am not using Java technologies and I have some doubt if this could be a good solution to structure a Spring Boot application.
I am developing a batch application using Spring Batch into a Spring Boot application (just to explain the general context, my question should be strictly related to the Spring Boot project structure).
Basically I have this UpdateInfoBatchApplication
that is the "main" classs starting my application:
@SpringBootApplication
@EnableBatchProcessing
@EnableScheduling
public class UpdateInfoBatchApplication {
@Bean
RestTemplate restTemplate() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
final String password = "MY_PSWD";
final String pfxPath = "/home/andrea/Documents/workspace-spring-tool-suite-4-4.11.0.RELEASE/UpdateInfoBatch/target/classes/static/certificate.pfx";
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = getHttpComponentsClientHttpRequestFactory(pfxPath,password);
RestTemplate restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
return restTemplate;
}
public static void main(String[] args) {
SpringApplication.run(UpdateInfoBatchApplication.class, args);
}
private static HttpComponentsClientHttpRequestFactory getHttpComponentsClientHttpRequestFactory(String pfxPath,String password) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = SSLContextBuilder
.create().loadKeyMaterial(new File(pfxPath),password.toCharArray(), password.toCharArray()).loadTrustMaterial(null, acceptingTrustStrategy).build();
HttpClient client = HttpClients.custom().setSSLContext(sslContext).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
return requestFactory;
}
}
Basically this class contains the main
method starting my Spring Boot application.
It also contain a restTemplate
method annotated with @Bean
annotation. It creates and return a custom RestTemplate
object (it is created calling the getHttpComponentsClientHttpRequestFactory
that itself return a HttpComponentsClientHttpRequestFactory
instance on which it is set an SSL client certificate needed to perform some APIs call).
It works fine but I am not sure that this UpdateInfoBatchApplication
class is a good place where to put this restTemplate
bean creation logic.
What do you think about? Could be a decent solution or is it pretty dirty?
You should put your bean creation logic under a class called "BeanConfig" or sth. I mostly group them according to context they have like putting password encoder bean in SecurityBeanConfig etc. Do not forget to annotate your class
@Configuration