Skip to content

tjnelsonfs/github-copilot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

10 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

GitHub Copilot in IntelliJ IDEA - Tutorial

Installation

  1. Go to Settings โ†’ Plugins
  2. Search for "GitHub Copilot"
  3. Install and restart IntelliJ
  4. Sign in with your GitHub account

Mode 1: Ask Mode (Copilot Chat)

Purpose: Get answers to coding questions without leaving your IDE.

How to Access:

  • Right-click in editor โ†’ Copilot โ†’ Open Copilot Chat
  • Or use shortcut: Ctrl+Shift+A (Windows/Linux) or Cmd+Shift+A (Mac) and search "Copilot Chat"

Example 1: Understanding Spring Boot Configuration

Prompt in Copilot Chat:

How do I configure a custom ObjectMapper in Spring Boot 3 with Java 21 features?

Expected Response: Copilot will explain the configuration and provide code like:

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }
}

Example 2: JUnit 5 Best Practices

Prompt:

Show me how to write a parameterized test in JUnit 5 for testing a REST controller

You'll get:

@ParameterizedTest
@CsvSource({
    "/api/users/1, 200",
    "/api/users/invalid, 400",
    "/api/users/999, 404"
})
void testUserEndpoints(String endpoint, int expectedStatus) {
    // Test implementation
}

Example 3: Mockito with Spring Boot

Prompt:

How do I mock a Spring Data JPA repository in JUnit 5 with Mockito?

Mode 2: Edit Mode (Inline Code Editing)

Purpose: Modify existing code directly with AI assistance.

How to Access:

  1. Select code block
  2. Right-click โ†’ Copilot โ†’ Edit Code
  3. Or press Ctrl+I (Windows/Linux) or Cmd+I (Mac)

Example 1: Convert Method to Use Java 21 Records

Original Code:

public class UserDTO {
    private Long id;
    private String name;
    private String email;
    
    // Constructor, getters, setters, equals, hashCode
}

Edit Prompt: "Convert this to a Java 21 record"

Result:

public record UserDTO(Long id, String name, String email) {}

Example 2: Add Validation Annotations

Original Code:

public record CreateUserRequest(
    String username,
    String email,
    String password
) {}

Edit Prompt: "Add Bean Validation annotations"

Result:

public record CreateUserRequest(
    @NotBlank(message = "Username is required")
    @Size(min = 3, max = 50)
    String username,
    
    @NotBlank(message = "Email is required")
    @Email
    String email,
    
    @NotBlank(message = "Password is required")
    @Size(min = 8)
    String password
) {}

Example 3: Refactor to Use Optional

Original Code:

public User findUser(Long id) {
    User user = userRepository.findById(id);
    if (user == null) {
        throw new UserNotFoundException("User not found");
    }
    return user;
}

Edit Prompt: "Refactor to use Optional and modern Java patterns"

Result:

public User findUser(Long id) {
    return userRepository.findById(id)
        .orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));
}

Example 4: Enhance Test Coverage

Original Test:

@Test
void testCreateUser() {
    User user = new User("john", "john@example.com");
    userService.create(user);
}

Edit Prompt: "Add proper assertions and mock verification"

Result:

@Test
void testCreateUser() {
    // Arrange
    User user = new User("john", "john@example.com");
    when(userRepository.save(any(User.class))).thenReturn(user);
    
    // Act
    User result = userService.create(user);
    
    // Assert
    assertNotNull(result);
    assertEquals("john", result.getUsername());
    assertEquals("john@example.com", result.getEmail());
    verify(userRepository, times(1)).save(user);
}

Mode 3: Agent Mode (Workspace Agent)

Purpose: Let Copilot work autonomously across multiple files, understanding your entire project context.

How to Access:

  • Open Copilot Chat
  • Click the agent icon in Copilot Chat window

Example 1: Generate Complete CRUD Service

Prompt in Agent Mode:

@workspace Create a complete CRUD service for a Product entity with:
- Entity class with JPA annotations (id, name, price, description)
- Repository interface
- Service class with business logic
- REST controller with all CRUD endpoints
- JUnit 5 tests with Mockito
Use Spring Boot 3 and Java 21 patterns

Copilot Agent will create multiple files:

  1. Product.java
@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(nullable = false)
    private BigDecimal price;
    
    private String description;
    
    // Constructors, getters, setters
}
  1. ProductRepository.java
  2. ProductService.java
  3. ProductController.java
  4. ProductServiceTest.java

Example 2: Add AOP Logging

Prompt:

@workspace Add AspectJ logging aspect that:
- Logs all method entries and exits in service layer
- Logs execution time
- Logs exceptions
- Uses SLF4J

Agent will create:

LoggingAspect.java

@Aspect
@Component
@Slf4j
public class LoggingAspect {
    
    @Around("execution(* com.example.service.*.*(..))")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        
        log.info("Entering {}.{}", className, methodName);
        long startTime = System.currentTimeMillis();
        
        try {
            Object result = joinPoint.proceed();
            long duration = System.currentTimeMillis() - startTime;
            log.info("Exiting {}.{} - Duration: {}ms", className, methodName, duration);
            return result;
        } catch (Exception e) {
            log.error("Exception in {}.{}: {}", className, methodName, e.getMessage());
            throw e;
        }
    }
}

Example 3: React Component with API Integration

Prompt:

@workspace Create a React component UserList that:
- Fetches users from /api/users endpoint
- Displays users in a table
- Has loading and error states
- Uses functional components and hooks

Agent creates:

UserList.jsx

import React, { useState, useEffect } from 'react';

function UserList() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetch('/api/users')
            .then(response => {
                if (!response.ok) throw new Error('Failed to fetch users');
                return response.json();
            })
            .then(data => {
                setUsers(data);
                setLoading(false);
            })
            .catch(err => {
                setError(err.message);
                setLoading(false);
            });
    }, []);

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error: {error}</div>;

    return (
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                {users.map(user => (
                    <tr key={user.id}>
                        <td>{user.id}</td>
                        <td>{user.name}</td>
                        <td>{user.email}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
}

export default UserList;

Example 4: Integration Test Setup

Prompt:

@workspace Create integration test configuration for Spring Boot 3 with:
- TestContainers for PostgreSQL
- Test application properties
- Base integration test class

Tips

For Ask Mode:

  • Be specific about Spring Boot version and Java version
  • Ask for explanations of error messages by pasting them
  • Request code reviews: "Review this code for potential issues"

For Edit Mode:

  • Select precise code blocks before invoking
  • Chain multiple edits for complex refactoring
  • Use clear, imperative instructions

For Agent Mode:

  • Always use @workspace prefix for multi-file operations
  • Provide complete requirements upfront
  • Review generated code carefully before committing
  • Agent understands your project structure automatically

Keyboard Shortcuts (Customize in Settings)

  • Open Copilot Chat: Ctrl+Shift+C โ†’ "Copilot Chat"
  • Inline Edit: Cmd+Shift+I
  • Accept Suggestion: Tab
  • Reject Suggestion: Esc

Common Use Cases

  1. Ask Mode: Quick questions, debugging help, best practices
  2. Edit Mode: Refactoring, adding features to existing code, fixing bugs
  3. Agent Mode: Generating new components, scaffolding, multi-file changes

Best Practices

  1. Always review generated code
  2. Add Copilot-generated code to your code review process
  3. Use descriptive variable names to help Copilot understand context
  4. Keep your project structure clean for better Agent mode results
  5. Combine modes: Use Ask to understand, Edit to modify, Agent to create

Troubleshooting

Copilot not suggesting: Check if file type is supported, verify subscription Irrelevant suggestions: Be more specific in comments and method names Agent not understanding context: Ensure project structure follows conventions


Happy coding with GitHub Copilot! ๐Ÿš€

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published