DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Using Kong Ingress Controller with Spring Boot Services
  • Building Microservices With gRPC and Java
  • How To Get Closer to Consistency in Microservice Architecture

Trending

  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Understanding Kernel Monitoring in Windows and Linux
  • Automated Data Extraction Using ChatGPT AI: Benefits, Examples
  • Machine Learning: A Revolutionizing Force in Cybersecurity
  1. DZone
  2. Coding
  3. Tools
  4. IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot

IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot

Explore productivity tips that can enhance your Java Spring Microservices development experience in IntelliJ, all made possible with the help of GitHub Copilot.

By 
Amol Gote user avatar
Amol Gote
DZone Core CORE ·
Jan. 23, 24 · Review
Like (8)
Save
Tweet
Share
10.0K Views

Join the DZone community and get the full member experience.

Join For Free

Have you ever wished for a coding assistant who could help you write code faster, reduce errors, and improve your overall productivity? In this article, I'll share my journey and experiences with GitHub Copilot, a coding companion, and how it has boosted productivity. The article is specifically focused on IntelliJ IDE which we use for building Java Spring-based microservices.

Six months ago, I embarked on a journey to explore GitHub Copilot, an AI-powered coding assistant, while working on Java Spring Microservices projects in IntelliJ IDEA. At first, my experience was not so good. I found the suggestions it provided to be inappropriate, and it seemed to hinder rather than help development work. But I decided to persist with the tool, and today, reaping some of the benefits, there is a lot of scope for improvement.

Common Patterns

Let's dive into some scenarios where GitHub Copilot has played a vital role.

Exception Handling

Consider the following method:

Java
 
private boolean isLoanEligibleForPurchaseBasedOnAllocation(LoanInfo loanInfo, PartnerBank partnerBank){
        boolean result = false;
        try {

            if (loanInfo != null && loanInfo.getFico() != null) {
                Integer fico = loanInfo.getFico();
                // Removed Further code for brevity
            } else {
                logger.error("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan info is null or FICO is null");
            }
        } catch (Exception ex) {
            logger.error("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - An error occurred while checking loan eligibility for purchase based on allocation, detail error:", ex);
        }
        return result;
    }


Initially, without GitHub Copilot, we would have to manually add the exception handling code. However, with Copilot, as soon as we added the try block and started adding catch blocks, it automatically suggested the logger message and generated the entire catch block. None of the content in the catch block was typed manually. Additionally, other logger.error in the else part is prefilled automatically by Co-Pilot as soon as we started typing in logger.error.

Mocks for Unit Tests

In unit testing, we often need to create mock objects. Consider the scenario where we need to create a list of PartnerBankFundingAllocation objects:

Java
 
List<PartnerBankFundingAllocation> partnerBankFundingAllocations = new ArrayList<>();
when(this.fundAllocationRepository.getPartnerBankFundingAllocation(partnerBankObra.getBankId(), "Fico")).thenReturn(partnerBankFundingAllocations);


If we create a single object and push it to the list:

Java
 
PartnerBankFundingAllocation partnerBankFundingAllocation = new PartnerBankFundingAllocation();
partnerBankFundingAllocation.setBankId(9);
partnerBankFundingAllocation.setScoreName("Fico");
partnerBankFundingAllocation.setScoreMin(680);
partnerBankFundingAllocation.setScoreMax(1000);
partnerBankFundingAllocations.add(partnerBankFundingAllocation);


GitHub Copilot automatically suggests code for the remaining objects. We just need to keep hitting enter and adjust values if the suggestions are inappropriate.

Java
 
PartnerBankFundingAllocation partnerBankFundingAllocation2 = new PartnerBankFundingAllocation();
partnerBankFundingAllocation2.setBankId(9);
partnerBankFundingAllocation2.setScoreName("Fico");
partnerBankFundingAllocation2.setScoreMin(660);
partnerBankFundingAllocation2.setScoreMax(679);
partnerBankFundingAllocations.add(partnerBankFundingAllocation2);


Logging/Debug Statements

GitHub Copilot also excels in helping with logging and debugging statements. Consider the following code snippet:

Java
 
if (percentage < allocationPercentage){
    result = true;
    logger.info("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan is eligible for purchase");
} else{
    logger.info("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan is not eligible for purchase");
}


In this example, all the logger information statements are auto-generated by GitHub Copilot. It takes into account the context of the code condition and suggests relevant log messages.

Code Commenting

It helps in adding comments at the top of the method. In the code snippet below, the comment above the method is generated by the Copilot. We just need to start typing in // This method.

Java
 
// THis method is used to get the loan program based on the product sub type
public static String getLoanProgram(List<Product> products, Integer selectedProductId) {
  String loanProgram = "";
  if (products != null && products.size() > 0) {
    Product product = products.stream().filter(p -> p.getProductId().equals(selectedProductId)).findFirst().orElse(null);
    if (product != null) {
      String productSubType = product.getProductSubType();
      switch (productSubType) {
        case "STANDARD":
          loanProgram = "Standard";
          break;
        case "PROMO":
          loanProgram = "Promo";
          break;
        default:
          loanProgram = "NA";
          break;
      }
    }

  }
  return loanProgram;
}


Alternatively, we can use a prompt like  // Q : What is this method doing?. Copilot will add the second line, // A : This method is used to log the payload for the given api name.

Java
 
// Q : What is this method doing?
// A : This method is used to log the payload for the given api name
public static void logPayload(String apiName, Object payload) {
  try {
    if (payload != null && apiName != null && apiName.trim().length() > 0) {
      ObjectMapper mapper = new ObjectMapper();
      String payloadResponse = mapper.writeValueAsString(payload);
      logger.info("UnderwritingUtility::logPayload - For api : " + apiName + ", payload : " + payloadResponse);
    } else {
      logger.error("UnderwritingUtility::logPayload - Either object was null of api name was null or empty");
    }
  } catch (Exception ex) {
    logger.error("UnderwritingUtility::logPayload - An error occurred while logging the payload, detail error : ", ex);
  }
}


Another example of a different method we type in a prompt: // Q : What is this method doing?. Copilot will add the second line, // A : This method is used to validate the locale from request, if locale is not valid then set the default locale.

Java
 
//Q - Whats below method doing?
//A - This method is used to validate the locale from request, if locale is not valid then set the default locale
public static boolean isLocaleValid(LoanQuoteRequest loanQuoteRequest){
  boolean result = false;
  try{
    if (org.springframework.util.StringUtils.hasText(loanQuoteRequest.getLocale())){
      String localeStr = loanQuoteRequest.getLocale();
      logger.info("UnderwritingUtility::validateLocale - Locale from request : " + localeStr);
      Locale locale = new Locale.Builder().setLanguageTag(localeStr).build();
      // Get the language part
      String language = locale.getLanguage();
      if (language.equalsIgnoreCase("en")){
        result = true;
        if (!localeStr.equalsIgnoreCase(UwConstants.DEFAULT_LOCALE_CODE)){
          loanQuoteRequest.setLocale(UwConstants.DEFAULT_LOCALE_CODE);
        }
      } else if (language.equalsIgnoreCase("es")){
        result = true;
        if (!localeStr.equalsIgnoreCase(UwConstants.SPANISH_LOCALE_CODE)){
          loanQuoteRequest.setLocale(UwConstants.SPANISH_LOCALE_CODE);
        }
      }
    } else{
      result = true;
      loanQuoteRequest.setLocale(UwConstants.DEFAULT_LOCALE_CODE);
    }
  } catch (Exception ex){
    logger.error("UnderwritingUtility::validateLocale - An error occurred, detail error : ", ex);
  }
  return result;
}


Closing Thoughts

The benefits of using GitHub Copilot in IntelliJ for Java Spring Microservices development are significant. It saves time, reduces errors, and allows us to focus on core business logic instead of writing repetitive code. As we embark on our coding journey with GitHub Copilot, here are a few tips:

  • Be patient and give it some time to learn and identify common coding patterns that we follow.
  • Keep an eye on the suggestions and adjust them as needed. Sometimes, it hallucinates.
  • Experiment with different scenarios to harness the full power of Copilot.
  • Stay updated with Copilot's improvements and updates to make the most of this cutting-edge tool.
  • We can use this in combination with ChatGPT. Here is an article on how it can help boost our development productivity.

Happy coding with GitHub Copilot!

GitHub intellij Java (programming language) microservice Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Using Kong Ingress Controller with Spring Boot Services
  • Building Microservices With gRPC and Java
  • How To Get Closer to Consistency in Microservice Architecture

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: