- Go to Settings โ Plugins
- Search for "GitHub Copilot"
- Install and restart IntelliJ
- Sign in with your GitHub account
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) orCmd+Shift+A(Mac) and search "Copilot Chat"
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);
}
}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
}Prompt:
How do I mock a Spring Data JPA repository in JUnit 5 with Mockito?
Purpose: Modify existing code directly with AI assistance.
How to Access:
- Select code block
- Right-click โ Copilot โ Edit Code
- Or press
Ctrl+I(Windows/Linux) orCmd+I(Mac)
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) {}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
) {}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));
}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);
}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
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:
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
}ProductRepository.javaProductService.javaProductController.javaProductServiceTest.java
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;
}
}
}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;Prompt:
@workspace Create integration test configuration for Spring Boot 3 with:
- TestContainers for PostgreSQL
- Test application properties
- Base integration test class
- 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"
- Select precise code blocks before invoking
- Chain multiple edits for complex refactoring
- Use clear, imperative instructions
- Always use
@workspaceprefix for multi-file operations - Provide complete requirements upfront
- Review generated code carefully before committing
- Agent understands your project structure automatically
- Open Copilot Chat:
Ctrl+Shift+Cโ "Copilot Chat" - Inline Edit:
Cmd+Shift+I - Accept Suggestion:
Tab - Reject Suggestion:
Esc
- Ask Mode: Quick questions, debugging help, best practices
- Edit Mode: Refactoring, adding features to existing code, fixing bugs
- Agent Mode: Generating new components, scaffolding, multi-file changes
- Always review generated code
- Add Copilot-generated code to your code review process
- Use descriptive variable names to help Copilot understand context
- Keep your project structure clean for better Agent mode results
- Combine modes: Use Ask to understand, Edit to modify, Agent to create
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! ๐