2024-04-11

  • To create a new object in spring without using the new keyword,using @Configuration & @Bean
@Configuration
@ComponentScan("com.example.account")
public class AppConfig{
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    Accounts accounts(){
        return new Accounts();
    }
}

Now autowire RestTemplate or Accounts in the service layer, this is the standard way of creating new objects in spring using bean definitions

  • Rest Template
@Autowired
RestTemplate restTemplate;

@Override
public AccountResponseDto addNewAccountCustomer(AccountRequestDto accountDto){
    String url="http://localhost:8081/api/v1/customer/{id}"
    ResponseEntity<CustomerDto> response=restTemplate.getForEntity(url,CustomerDto.class,accountDto.customerId());

}