Micronaut Framework Cheatsheet

Micronaut is a modern, JVM-based framework designed for building modular and microservices-based applications. It boasts features like low memory consumption, fast startup times, and efficient use of resources. Whether you’re a seasoned Micronaut developer or just getting started, having a cheatsheet handy can be a great way to streamline your development process. In this cheatsheet, we’ll cover some key concepts and commands to accelerate your Micronaut development.

1. Getting Started

1.1 Create a Micronaut Project

mn create-app my-micronaut-app

1.2 Run the Application

./gradlew run

2. Controllers and Endpoints

2.1 Create a Controller

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/api")
public class MyController {

    @Get("/hello")
    public String hello() {
        return "Hello, Micronaut!";
    }
}

2.2 Path Variables

@Get("/greet/{name}")
public String greet(String name) {
    return "Hello, " + name + "!";
}

3. Dependency Injection

3.1 Inject a Bean

import javax.inject.Inject;

@Controller("/example")
public class ExampleController {

    @Inject
    private MyService myService;

    // Controller methods using myService
}

4. Configuration

4.1 Configuration Properties

my:
  property:
    value: 42
@Value("${my.property.value}")
private int myPropertyValue;

5. Data Persistence with JPA

5.1 Define an Entity

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String title;

    // Getters and setters
}

5.2 Repository Interface

import io.micronaut.data.annotation.Repository;
import io.micronaut.data.repository.CrudRepository;

@Repository
public interface BookRepository extends CrudRepository<Book, Long> {

    List<Book> findByTitle(String title);
}

6. Testing

6.1 Unit Testing with JUnit

import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

@MicronautTest
public class MyControllerTest {

    // Test methods
}

7. Logging

7.1 Log a Message

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller("/log")
public class LogController {

    private static final Logger LOG = LoggerFactory.getLogger(LogController.class);

    @Get("/message")
    public String logMessage() {
        LOG.info("This is a log message");
        return "Logged!";
    }
}

8. Security

8.1 Securing Endpoints

import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;

@Controller("/secure")
@Secured(SecurityRule.IS_AUTHENTICATED)
public class SecureController {

    // Secured methods
}

This Micronaut cheatsheet provides a quick reference for common tasks and concepts, helping you navigate the framework efficiently. Whether you’re working on controllers, configuring your application, or dealing with data persistence, this cheatsheet is a handy companion for your Micronaut development journey. Keep exploring and building with Micronaut to leverage its powerful features for creating robust and efficient applications.

FAQ

1. What is Micronaut, and how does it differ from other JVM frameworks?

Micronaut is a modern, JVM-based framework designed for building modular and microservices-based applications. It stands out for its low memory consumption, fast startup times, and efficient resource utilization. Unlike traditional frameworks, Micronaut achieves these benefits through compile-time processing and native image generation.

2. How can I create a new Micronaut project?

You can create a new Micronaut project using the following command:
mn create-app my-micronaut-app
This command initializes a new Micronaut project with default settings, ready for you to start development.

3. How do I define and use configuration properties in Micronaut?

To define configuration properties, you can use YAML files. For example:
my: property: value: 42
You can then inject these properties into your code using the @Value annotation, like this:
@Value("${my.property.value}") private int myPropertyValue;

4. Can Micronaut be used for data persistence with JPA?

Yes, Micronaut provides seamless integration with JPA (Java Persistence API) for data persistence. You can define entities, repositories, and use standard JPA annotations for database operations. Micronaut simplifies the process of working with databases in your applications.

5. How do I secure my Micronaut endpoints?

Micronaut offers security features that allow you to secure your endpoints easily. You can use the @Secured annotation along with predefined security rules to restrict access to specific controllers or methods. For example:
import io.micronaut.security.annotation.Secured; import io.micronaut.security.rules.SecurityRule; @Controller("/secure") @Secured(SecurityRule.IS_AUTHENTICATED) public class SecureController { // Secured methods }
This ensures that only authenticated users can access the methods within the SecureController.