August 31, 2018

Micronaut Mastery: Change The Default Package For Generated Classes

When we use the Micronaut command line commands to generate controllers, beans and more, the classes will have a default package name. We can use a fully qualified package name for the class we want to generate, but when we only define a class name, Micronaut will use a default package name automatically. We can set the default package for an application when we first create an application with the create-app command. But we can also alter the default package name for an existing Micronaut application.

To set the default package name when we create a new application we must include the package name in our application name. For example when we want to use the default package name mrhaki.micronaut for an application that is called book-service we must use the following create-app command:

$ mn create-app mrhaki.micronaut.book-service
| Generating Java project.....
| Application created at /Users/mrhaki/Projects/mrhaki.com/blog/posts/samples/micronaut/book-service
$ tree src
src
├── main
│   ├── java
│   │   └── mrhaki
│   │       └── micronaut
│   │           └── Application.java
│   └── resources
│       ├── application.yml
│       └── logback.xml
└── test
    └── java
        └── mrhaki
            └── micronaut

9 directories, 3 files

Notice the tree structure reflects the structure for the package mrhaki.micronaut.
When we invoke the create-controller book command the generated files use the package name mrhaki.micronaut:

$ mn create-controller book
| Rendered template Controller.java to destination src/main/java/mrhaki/micronaut/BookController.java
| Rendered template ControllerTest.java to destination src/test/java/mrhaki/micronaut/BookControllerTest.java
$

We can change the default package name for an existing application as well. We must edit the file micronaut-cli.yml in the root of our project and change the property defaultPackage. In the following example we use the sed command on MacOS to replace the current default package with com.mrhaki.microanut, but we could of course also use any text editor to make the change:

$ cat micronaut-cli.yml
profile: service
defaultPackage: mrhaki.micronaut
---
testFramework: junit
sourceLanguage: java
$ sed -E -i '' 's/(defaultPackage:) .*/\1 com\.mrhaki\.micronaut/g' micronaut-cli.yml
$ cat micronaut-cli.yml
profile: service
defaultPackage: com.mrhaki.micronaut
---
testFramework: junit
sourceLanguage: java

Let's generate a new controller and see if our new default package name for the application is used:

$ mn create-controller author
| Rendered template Controller.java to destination src/main/java/com/mrhaki/micronaut/AuthorController.java
| Rendered template ControllerTest.java to destination src/test/java/com/mrhaki/micronaut/AuthorControllerTest.java
$

Written with Micronaut 1.0.0.M4.