Google Dagger Stub Generator - VS Code Extension

📋 Introduction
This VS Code extension solves a common problem with the Google Dagger dependency injection framework: IDEs cannot recognize auto-generated DaggerXXX classes.
When you use DaggerConfigComponent.create(), the IDE shows an error because this class doesn't exist before compilation. This extension automatically generates stub classes for all @Component interfaces, allowing the IDE to correctly recognize and provide autocomplete functionality.
But that's just the beginning! This extension provides a comprehensive set of developer tools to enhance your Dagger development experience, including advanced error diagnosis, interactive dependency graphs, and intelligent code navigation.
✨ Features
🎯 Core Features
- 🔍 Auto-Scan: Automatically scans all interfaces annotated with
@Component and @Subcomponent in your project
- 🎯 Auto-Generate: Automatically generates corresponding
DaggerXXX stub classes with full support for:
create() static method
builder() static method
Builder inner class
@Component.Factory interface with parameters
- 🔄 Real-time Updates: Watches file changes and automatically updates stub classes
- 🛡️ Safety Mechanism: Intelligently distinguishes between Google Dagger and Spring Boot's
@Component annotations
- 🌐 Internationalization: Full support for English and Traditional Chinese with instant language switching
- 📝 Code Snippets: Quick templates with bilingual educational comments for Module, Component, Subcomponent, @Provides, and @Binds
- 🔧 Build Tool Auto-Configuration: Automatically detects Gradle/Maven and configures generated sources paths in VS Code settings
- ✍️ Spell Checking: CSpell integration with custom Dagger dictionary to prevent false positives
🧭 Navigation & Code Intelligence
🌳 Dependency Tree Visualization
🚀 Quick Boilerplate Generation
- Right-click Context Menu:
- Right-click on any interface → "Create Dagger Component"
- Right-click on any interface → "Create Dagger Subcomponent"
- Right-click on any class → "Create Dagger Module"
- Smart Templates: Automatically generates:
- Package declarations
- Import statements
- Annotation configurations
- Basic structure with TODO comments (i18n-aware)
🎨 Hilt Support
- Automatic Hilt Detection:
- Identifies
@HiltAndroidApp and @AndroidEntryPoint annotations
- Automatically generates stubs for Hilt-generated classes (e.g.,
DaggerHiltXXX)
- Hilt-aware Analysis: Understands Hilt-specific patterns and dependencies
🔧 Advanced Analysis
🛠️ Technical Excellence
Robust Parsing:
- Uses
java-parser for accurate AST-based code analysis
- Graceful fallback to regex parsing if
java-parser is unavailable
- Handles complex Java syntax (generics, annotations, multi-line signatures)
Performance Optimized:
- Incremental updates (only regenerates changed components)
- Efficient file watching
- Smart caching of analysis results
🚀 Installation
Method 1: Install from VS Code Marketplace (Recommended)
- Open VS Code
- Go to Extensions view (
Ctrl+Shift+X or Cmd+Shift+X on Mac)
- Search for "Google Dagger Stub Generator" or "Dagger Stub Generator"
- Click "Install"
Method 2: Install from VSIX Package
- Download the latest
.vsix file from Releases
- Open VS Code command palette (
Ctrl+Shift+P or Cmd+Shift+P on Mac)
- Run "Extensions: Install from VSIX..."
- Select the downloaded
.vsix file
Method 3: Install from Source (Development Mode)
- Clone or download this repository
- Open a terminal and navigate to the extension directory:
cd vscode-dagger-extension
- Install dependencies:
npm install
- Compile the extension:
npm run compile
- In VS Code, press
F5 to launch the extension development host
Method 4: Package and Install
- Install
vsce (VS Code Extension Manager):
npm install -g @vscode/vsce
- Package the extension:
cd vscode-dagger-extension
npm run package
- Install the generated
.vsix file in VS Code
⚙️ Configuration Options
You can configure the following options in VS Code settings (settings.json):
{
"daggerStubGenerator.enabled": true, // Enable/disable extension
"daggerStubGenerator.stubDirectory": ".dagger-stubs", // Stub class directory
"daggerStubGenerator.autoGenerate": true, // Auto-generate stubs
"daggerStubGenerator.watchPattern": "**/*Component.java", // File pattern to watch
"daggerStubGenerator.language": "auto" // Extension language: "auto" (use VS Code language), "en", or "zh-TW"
}
Note: The language setting supports real-time updates. When you change the language setting, the extension will automatically update without requiring a window reload.
📖 Usage
Automatic Mode (Recommended)
After the extension starts, it will automatically:
- Detect build tool (Gradle/Maven) and configure generated sources paths
- Scan all
@Component and @Subcomponent interfaces in your project
- Generate corresponding stub classes
- Monitor file changes and automatically update
- Provide hover information, navigation, and tree view
The extension automatically detects your project's build tool (Gradle or Maven) and configures the generated sources paths in VS Code's Java project settings:
- Gradle: Detects
build.gradle or build.gradle.kts and configures:
build/generated/sources/annotationProcessor/java/main
- Custom sourceSets from your build configuration
- Maven: Detects
pom.xml and configures:
target/generated-sources/annotations
- Custom source paths from build configuration
When configuration is updated, you'll receive a notification with an option to reload the window.
Manual Commands
Use the command palette (Ctrl+Shift+P or Cmd+Shift+P) to access:
- Dagger: Generate Stubs - Manually trigger stub generation
- Dagger: Reload Project - Reload the project and regenerate all stubs
- Create Dagger Component - Generate a new Component template
- Create Dagger Subcomponent - Generate a new Subcomponent template
- Create Dagger Module - Generate a new Module template
- Dagger: Open Dependency Graph - Open interactive dependency graph in editor
- Dagger: Refresh Dependency Graph - Refresh the dependency graph
- Dagger: Refresh Options - Dropdown menu to refresh Tree or Graph
- Dagger: Filter Options - Dropdown menu for filter settings (Hilt Only, Problems Only)
- Dagger: Search in Tree - Search for components, modules, or types
- Dagger: Filter by Scope - Filter components by scope
- Dagger: Clear Filters - Clear all active filters
Using Code Snippets
Type the following prefixes in a Java file to quickly generate Dagger boilerplate:
dagger-module - Generate a complete Module with @Provides method
dagger-component - Generate a complete Component interface
dagger-subcomponent - Generate a Subcomponent with Builder
dagger-provides - Generate a single @Provides method
dagger-binds - Generate a single @Binds method
All snippets include bilingual (English/Chinese) comments explaining Dagger concepts.
Using the Dagger Explorer
- Open the Dagger Explorer in the sidebar (look for the Dagger icon)
- Browse all Components in your project
- Expand nodes to see Modules, Dependencies, and Provided Types
- Click on any node to navigate to its definition
- Use the toolbar buttons:
- Refresh Options (dropdown): Refresh Tree or Graph
- Open Graph: Open interactive dependency graph
- Search: Search for specific components or types
- Filter by Scope: Filter components by scope
- Filter Options (dropdown): Toggle Hilt Only or Problems Only filters
- Clear Filters: Remove all active filters
Using the Interactive Dependency Graph
- Open the graph from Dagger Explorer toolbar or command palette
- The graph opens as a webview panel in the editor area
- Navigate:
- Pan: Click and drag
- Zoom: Mouse wheel or pinch gesture
- Search: Use the search box to find specific nodes
- Filter: Toggle node type filters (Components, Modules, Bindings, Types)
- Jump to Code: Click any node to navigate to its source code
- Refresh: Click refresh button to update graph with latest changes
Using Quick Fix
When you see an error in the Problems panel:
- Click the lightbulb icon (💡) or press
Ctrl+. (Windows/Linux) / Cmd+. (Mac)
- Select from available Quick Fix options:
- Create @Provides method: Adds a @Provides method to the current file
- Create @Binds method: Adds a @Binds method to the current file
- Create new Module: Creates a new Module file with the binding
- Remove duplicate: Deletes duplicate binding methods
- Remove scope: Removes incompatible scope annotations
- Add Subcomponent to Module: Adds Subcomponent to Module's subcomponents parameter
- The code is automatically inserted or modified
Navigation Features
Jump to Provider:
- Place your cursor on an
@Inject field
- Press
F12 (Go to Definition) or Ctrl+Click
- Navigate directly to the
@Provides or @Binds method
Hover Information:
- Hover over
@Inject fields to see binding details
- Hover over
@Qualifier annotations to see their definitions
📁 Generated File Structure
Assuming you have the following Component:
package arc.ignis.lin;
@Component(modules = ConfigModule.class)
public interface ConfigComponent {
ConfigService configService();
}
The extension will generate in .dagger-stubs/arc/ignis/lin/ directory:
.dagger-stubs/
└── arc/
└── ignis/
└── lin/
└── DaggerConfigComponent.java
The generated stub class includes:
create() static method
builder() static method
Builder inner class
Factory interface (if @Component.Factory is present)
Example Generated Stub
package arc.ignis.lin;
import dagger.Component;
import javax.inject.Provider;
public final class DaggerConfigComponent implements ConfigComponent {
private DaggerConfigComponent() {
throw new UnsupportedOperationException("This is a stub class for IDE support only.");
}
public static ConfigComponent create() {
throw new UnsupportedOperationException("This is a stub class for IDE support only.");
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private Builder() {}
public Builder configModule(ConfigModule configModule) {
throw new UnsupportedOperationException("This is a stub class for IDE support only.");
}
public ConfigComponent build() {
throw new UnsupportedOperationException("This is a stub class for IDE support only.");
}
}
@Override
public ConfigService configService() {
throw new UnsupportedOperationException("This is a stub class for IDE support only.");
}
}
🔧 How It Works
1. Scanning Phase
- Parses Java files to find all interfaces annotated with
@Component and @Subcomponent
- Uses
java-parser for accurate AST-based parsing (with regex fallback)
- Extracts package names, class names, methods, modules, and dependencies
2. Security Check
Verifies the use of Google Dagger's dagger.Component by checking:
- ✅
import dagger.Component; statement
- ✅
import dagger.*; wildcard import
- ✅ Fully qualified name
@dagger.Component
- ❌ Excludes
org.springframework.stereotype.Component (Spring Boot)
- ❌ Excludes other non-Google Dagger
@Component annotations
This ensures that even if the project uses both Google Dagger and Spring Boot, it can correctly identify Google Dagger Components.
3. Analysis Phase
- Extracts Component metadata (package, methods, modules, dependencies)
- Analyzes
@Component.Factory interfaces and their method signatures
- Identifies Subcomponents and their parent relationships
- Analyzes bindings (
@Provides, @Binds, constructor injection)
- Extracts qualifiers and map keys
4. Generation Phase
- Generates corresponding stub classes based on analysis results
- Includes all public methods and factory methods
- Preserves package structure
- Adds proper imports and annotations
5. Monitoring Phase
- Monitors file changes using VS Code's file watcher
- Automatically updates stubs when Components are modified
- Refreshes hover information and tree view
🎨 Feature Showcase
Error Diagnosis & Quick Fix
Missing Binding Detection:
- Detects when a Component requires a type that cannot be provided
- Checks for @Inject constructors, @BindsInstance, and existing bindings
- Provides context-aware Quick Fix options
Duplicate Binding Detection:
- Identifies when the same type is bound multiple times (excluding Multibindings)
- Offers to remove duplicate bindings
Scope Incompatibility Detection:
- Warns when a binding's scope is incompatible with its Component's scope
- Offers to remove the incompatible scope annotation
Circular Dependency Detection:
- Detects circular dependencies between Components
- Shows the dependency cycle path
Interactive Dependency Graph
Visualize your entire Dagger dependency structure:
- See all Components, Modules, Bindings, and their relationships
- Navigate by panning and zooming
- Search and filter to find specific items
- Click nodes to jump directly to source code
Hover over an @Inject field:
@Inject
MyService service; // ← Hover here
Displays:
- Provided by:
@Provides method in AppModule
- Scope:
@Singleton
- Binding Type:
@Provides
- Module:
AppModule
- Qualifier:
@Named("production")
Navigation
Click on @Inject field → Navigate to provider:
@Inject
MyService service; // ← Ctrl+Click or F12
Jumps to:
@Module
public class AppModule {
@Provides
@Singleton
MyService provideMyService() { // ← Lands here
return new MyServiceImpl();
}
}
Dagger Explorer
Visualize your dependency graph with rich information:
📦 Dagger Explorer
├── 📦 AppComponent (@Singleton) [5 types] [Hilt] ⚠️
│ ├── 📁 Modules (2)
│ │ ├── AppModule
│ │ │ ├── MyService provideMyService() (@Singleton)
│ │ │ └── ApiClient provideApiClient() (@Singleton)
│ │ └── NetworkModule
│ │ └── Retrofit provideRetrofit() (@Singleton)
│ ├── 🔗 Dependencies (1)
│ │ └── DatabaseComponent
│ └── 📋 Provided Types (5)
│ ├── MyService
│ ├── ApiClient
│ └── ...
└── 📦 ActivityComponent [3 types]
└── ...
Legend:
[@Singleton] - Component scope
[5 types] - Number of provided types
[Hilt] - Hilt component indicator
⚠️ - Component has problems (e.g., missing bindings)
Interactive Dependency Graph
The dependency graph provides a visual representation of your Dagger dependency structure:
- Nodes: Color-coded by type (Components, Modules, Bindings, Types)
- Edges: Show relationships (uses, provides, depends on)
- Layout: Automatic force-directed layout for easy navigation
- Interactivity: Click nodes to jump to code, search and filter for specific items
⚠️ Important Notes
- Stub Classes are IDE-only: Generated stub classes are only for IDE recognition; actual execution still requires the implementation classes generated by the Google Dagger compiler
- UnsupportedOperationException: Methods in stub classes will throw
UnsupportedOperationException, which is normal and expected
- Git Ignore: It is recommended to add the
.dagger-stubs directory to .gitignore and not commit it to version control
- Source Path: Make sure
.dagger-stubs is added to your Java project's source path in .vscode/settings.json:
{
"java.project.sourcePaths": [
"src",
".dagger-stubs"
]
}
🐛 Troubleshooting
Issue: Stub classes are not automatically generated
Solution:
- Check if
daggerStubGenerator.enabled is true in settings
- Check if
daggerStubGenerator.autoGenerate is true
- Manually execute the "Dagger: Generate Stubs" command
- Check the Output panel for error messages
Issue: IDE still shows errors
Solution:
- Confirm stub classes are correctly generated in the
.dagger-stubs directory
- Add the
.dagger-stubs directory to the Java project's source path (see above)
- Reload the VS Code window (
Ctrl+Shift+P → "Developer: Reload Window")
- If using Java Language Server, you might need to restart it
Issue: Navigation doesn't work
Solution:
- Ensure the Java extension is installed and enabled
- Check that the source files are properly indexed
- Try reloading the window
Issue: Dagger Explorer is empty
Solution:
- Click the refresh button in the Dagger Explorer toolbar
- Run "Dagger: Generate Stubs" command
- Ensure your Components are properly annotated with
@Component from dagger.Component
- Check if filters are active (try "Clear Filters" command)
Issue: Quick Fix not appearing
Solution:
- Ensure the error is from the Dagger extension (check source in Problems panel)
- Make sure the file is saved
- Try reloading the window
- Check that the extension is enabled in settings
Issue: Dependency graph is empty or not updating
Solution:
- Click the refresh button in the graph panel
- Run "Dagger: Generate Stubs" to ensure components are scanned
- Check that Components have Modules or Dependencies defined
- Try closing and reopening the graph panel
📝 Example Usage
Before Using This Extension
// ❌ IDE shows error: "Cannot resolve symbol 'DaggerConfigComponent'"
ConfigComponent component = DaggerConfigComponent.create();
ConfigService service = component.configService();
After Using This Extension
// ✅ IDE recognizes DaggerConfigComponent with full autocomplete!
ConfigComponent component = DaggerConfigComponent.create();
ConfigService service = component.configService();
@Inject
ConfigService service; // ← Hover to see: Provided by AppModule, @Singleton
With Navigation
@Inject
ConfigService service; // ← Ctrl+Click to jump to @Provides method
With Quick Fix
When you see a missing binding error:
@Component(modules = AppModule.class)
public interface AppComponent {
UserService userService(); // ← Error: Missing binding
}
Quick Fix options:
Create @Provides method → Adds to AppModule:
@Provides
UserService provideUserService() {
// TODO: Implement provider logic
return new UserService();
}
Create new Module → Creates UserServiceModule with the binding
Create @Binds method → Adds abstract @Binds method (if using interface)
🌐 Internationalization
This extension supports multiple languages:
- English (default)
- Traditional Chinese (繁體中文)
The language can be set in VS Code settings:
{
"daggerStubGenerator.language": "auto" // or "en" or "zh-TW"
}
When set to "auto", the extension will use VS Code's current language setting. Language changes take effect immediately without requiring a window reload.
🤝 Contributing
Contributions are welcome! Please feel free to submit Issues and Pull Requests.
Development Setup
- Fork the repository
- Clone your fork
- Install dependencies:
npm install
- Make your changes
- Test your changes:
npm run compile
- Submit a Pull Request
📄 License
MIT License - see LICENSE file for details
🙏 Acknowledgments
Made with ❤️ for the Dagger community