eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

From the creator of ebean, Avaje Inject is a JVM-based framework for advanced compile-time Dependency Injection (DI). It takes the approach of generating readable source code to support various DI operations. Avaje reads JSR-330 annotated beans and generates classes to collect bean instances from our application and use them at the appropriate time.

2. Dependency Injection

As a bit of a reminder, Dependency Injection is a concrete application of the Inversion of Control principle in which the program controls its own flow.

Different frameworks implement dependency injection in different ways. In particular, one of the most notable of these differences is whether the injection happens at run-time or compile-time.

Run-time DI is usually based on reflection. It’s simple to use but slow at runtime. The premier example of a runtime DI framework is Spring.

Compile-time DI, on the other hand, is typically based on code generation. This means that all the heavyweight operations are performed during the compilation stage. It generally performs faster as it eliminates the need for intensive reflection or classpath scanning at runtime.

Avaje has decided to rely totally on annotation processing for compile-time source generation.

3. Maven/Gradle Configuration

To use Avaje Inject in a project, we’ll need to add the avaje-inject dependencies to our pom.xml:

<dependency>
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject</artifactId>
    <version>9.5</version>
</dependency>

<dependency>
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject-test</artifactId>
    <version>9.5</version>
    <scope>test</scope>
</dependency>

Furthermore, we’ll also need to include the inject code generator to read our annotated classes and generate the code used for the injection. It’s added with an optional scope because the generator is only required at compile time:

<dependency> 
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject-generator</artifactId>
    <version>9.5</version>
    <scope>provided</scope>
    <optional>true</optional>
</dependency>

If we’re using Gradle, we’ll include these dependencies as:

implementation('io.avaje:avaje-inject:9.5')
annotationProcessor('io.avaje:avaje-inject-generator:9.5')

testImplementation('io.avaje:avaje-inject-test:9.5')
testAnnotationProcessor('io.avaje:avaje-inject-generator:9.5')

Now that we have avaje-inject in our project, let’s create a sample application to see how it works.

4. Implementation

For our example, we’ll try to build a knight by injecting his weapons as dependencies. The avaje-inject generator will read all various annotations at compile-time and generate DI code in target/generated-sources/annotations.

4.1. @Singleton and @Inject

In a similar manner to Spring’s @Component, Avaje uses the standard JSR-330 annotation @Singleton to mark a class as a bean. To inject dependencies, we add the @Inject annotations to fields or the constructor. The generated DI code is in the same package, so to use field/method injection, those elements must be public or package-private.

Let’s have a look at our Knight class, which has two weapon dependencies:

@Singleton
public class Knight {

  private Sword sword;

  private Shield shield;

  @Inject
  public Knight(Sword sword, Shield shield) {
    this.sword = sword;
    this.shield = shield;
  }
  //standard getters and setters
}

The code generator will read the annotations and generate a class to gather the dependencies and register the bean:

@Generated("io.avaje.inject.generator")
public final class Knight$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(Knight.class)) {
      var bean = new Knight(builder.get(Sword.class,"!sword"), builder.get(Shield.class,"!shield"));
      builder.register(bean);
    }
  }
}

This class checks for existing Knight classes and then retrieves the dependencies from the current scope.

4.2. @Factory and @Bean

Like Spring’s @Configuration classes, we can annotate a class with @Factory and its methods with @Bean to mark the class as a factory that creates beans.

In the ArmsFactory class, we use this to provide the knight’s armaments to the application scope:

@Factory
public class ArmsFactory {

  @Bean
  public Sword provideSword() {
    return new Sword();
  }

  @Bean
  public Brand provideShield() {
    return new Shield(25);
  }
}

The code generator will read the annotations and generate a class to call the constructors and factory methods:

@Generated("io.avaje.inject.generator")
public final class ArmsFactory$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(ArmsFactory.class)) {
      var bean = new ArmsFactory();
      builder.register(bean);
    }
  }

  public static void build_provideEngine(Builder builder) {
    if (builder.isAddBeanFor(Sword.class)) {
      var factory = builder.get(ArmsFactory.class);
      var bean = factory.provideEngine();
      builder.register(bean);
    }
  }

  public static void build_provideBrand(Builder builder) {
    if (builder.isAddBeanFor(Shield.class)) {
      var factory = builder.get(ArmsFactory.class);
      var bean = factory.provideBrand();
      builder.register(bean);
    }
  }
}

4.3. @PostConstruct and @PreDestroy

Avaje can use lifecycle methods to attach custom actions to bean creation and destruction. @PostConstruct methods execute after the BeanScope finishes wiring all the beans, and @Predestroy runs when the BeanScope is closed.

Given that @PostConstruct methods will execute after all beans have wired, we can add a BeanScope parameter to configure further using the completed BeanScope. The below Ninja class uses @PostConstruct to set its members with beans from the application scope:

@Singleton
public class Ninja {

  private Sword sword;

  @PostConstruct
  void equip(BeanScope scope) {
    sword = scope.get(Sword.class);
  }

  @PreDestroy
  void dequip() {
    sword = null;
  }

//getters/setters
}

The code generator will read the annotations and generate a class to call the constructor and register the lifecycle methods:

@Generated("io.avaje.inject.generator")
public final class Ninja$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(Ninja.class)) {
      var bean = new Ninja();
      var $bean = builder.register(bean);
      builder.addPostConstruct($bean::equip);
      builder.addPreDestroy($bean::dequip);
    }
  }
}

5. Generated Module

At compile time, the avaje-inject-generator reads all the bean definitions and determines the wiring of all the beans. It then generates a Module class representing our application and its dependencies.

For all the above classes, the below IntroModule is generated to execute all the injections to add to the application scope. We can see the definition and wiring order of all the beans in the application:

@Generated("io.avaje.inject.generator")
@InjectModule()
public final class IntroModule implements Module {

  private Builder builder;

  @Override
  public Class<?>[] classes() {
    return new Class<?>[]{
      com.baeldung.avaje.intro.ArmsFactory.class,
      com.baeldung.avaje.intro.Knight.class,
      com.baeldung.avaje.intro.Ninja.class,
      com.baeldung.avaje.intro.Shield.class,
      com.baeldung.avaje.intro.Sword.class,
    };
  }

  /**
   * Creates all the beans in order based on constructor dependencies.
   * The beans are registered into the builder along with callbacks for
   * field/method injection, and lifecycle support.
   */
  @Override
  public void build(Builder builder) {
    this.builder = builder;
    build_intro_ArmsFactory();
    build_intro_Ninja();
    build_intro_Sword();
    build_intro_Shield();
    build_intro_Knight();
  }

  @DependencyMeta(type = "com.baeldung.avaje.intro.ArmsFactory")
  private void build_intro_ArmsFactory() {
    ArmsFactory$DI.build(builder);
  }

  @DependencyMeta(type = "com.baeldung.avaje.intro.Ninja")
  private void build_intro_Ninja() {
    Ninja$DI.build(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Sword",
      method = "com.baeldung.avaje.intro.ArmsFactory$DI.build_provideSword",
      dependsOn = {"com.baeldung.avaje.intro.ArmsFactory"})
  private void build_intro_Sword() {
    ArmsFactory$DI.build_provideSword(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Shield",
      method = "com.baeldung.avaje.intro.ArmsFactory$DI.build_provideShield",
      dependsOn = {"com.baeldung.avaje.intro.ArmsFactory"})
  private void build_intro_Shield() {
    ArmsFactory$DI.build_provideShield(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Knight",
      dependsOn = {
        "com.baeldung.avaje.intro.Sword",
        "com.baeldung.avaje.intro.Shield"
      })
  private void build_intro_Knight() {
    Knight$DI.build(builder);
  }
}

6. Retrieving Beans With BeanScope

To manage dependencies, Avaje’s BeanScope loads and executes all the generated Module classes from the application and its dependencies and stores the created beans to be retrieved later.

Let’s construct the BeanScope and receive our Knight class, fully equipped with Sword and Shield:

final var scope = BeanScope.builder().build();
final var knight = scope.get(Knight.class);

assertNotNull(knight);
assertNotNull(knight.sword());
assertNotNull(knight.shield());
assertEquals(25, knight.shield().defense());

7. Component Testing With @InjectTest

The @InjectTest annotation is useful when we need to bootstrap a bean scope for our tests. The annotation works by creating a test BeanScope that will be utilized.

We can use Mockito’s @Mock annotation to add mock objects to the test’s BeanScope. When we use the @Mock annotation on a field, the mock will be injected into the field, as well as registered in the test scope. The mock will replace any existing bean of the same type in the scope.

If no bean of the same type is defined, a new one will be added. This is useful for component tests where a particular bean, like an external service, needs to be mocked.

Here, we use the injected Shield mock to stub the defense method. Then, we use @Inject to get the knight bean from the test scope to verify that it contains the mocked shield:

@InjectTest
class ExampleInjectTest {

  @Mock Shield shield;

  @Inject Knight knight;

  @Test
  void givenMockedShield_whenGetShield_thenShieldShouldHaveMockedValue() {

    Mockito.when(shield.defense()).thenReturn(0);
    assertNotNull(knight);
    assertNotNull(knight.sword());
    assertEquals(knight.shield(), shield);
    assertEquals(0, knight.shield().defense());
  }
}

8. Conclusion

In this article, we went through how to set up and use Avaje Inject with a basic example. We’ve seen how it uses code generation to perform various DI actions and how to create tests and use mocks.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)