Taras K
Taras K

Reputation: 105

Custom Micronaut module/jar with auto-configurations

Can't find a proper working example how to write own modules/libs with auto-configuration.
Can someone explain how to write proper modules for micronaut app?

Tried to load @Factory class and adding package-info.java with @Configuration annotation but that didn't help. Also was adding proper package to scan in main class like this Micronaut.build(args).packages("com.mypackage").start()

Sample:

package com.mypackage;

    public class FooService {
      public void bar() {

      }
    }


package com.mypackage;

import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import javax.inject.Singleton;

@Factory
public class FooFactory {

    @Bean
    @Singleton
    public FooService fooService() {
        return new FooService();
    }
}


//com.mypackage.package-info.java
@Configuration
package com.mypackage;

import io.micronaut.context.annotation.Configuration;

Upvotes: 1

Views: 1146

Answers (2)

Taras K
Taras K

Reputation: 105

The actual problem was in Maven.
Micronaut Annotation Processor was not triggered by maven-compiler-plugin.

The solution was to configure annotation processors in maven-compile-plugin:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>${maven-compiler-plugin.source}</source>
                <target>${maven-compiler-plugin.target}</target>
                <encoding>${maven-compiler-plugin.encoding}</encoding>
                <annotationProcessorPaths>
                    <!-- uncomment if you are using lombok -->
                    <!-- path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombok.version}</version>
                    </path -->
                    <path>
                        <groupId>io.micronaut</groupId>
                        <artifactId>micronaut-inject-java</artifactId>
                        <version>${micronaut.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>

Upvotes: 2

Mike Houston
Mike Houston

Reputation: 264

I learned a lot from looking at the handlebars view renderer.

For a configuration in your bean, you need:

  1. Create an interface with getters for your configuration options.
  2. Create an implementation of it. Finally, in your bean's constructor,
  3. Add the configuration interface as an argument.

When Micronaut creates your bean, it will read the application.yml file and set the values in your configuration impl class. Then it will build your bean with the config value as an argument.

Upvotes: 0

Related Questions