Micronaut Mastery: Change the Default Package for Generated Classes
In this post, we go over the terminal commands and YAML you'll need to know. Read on to achieve mastery!
Join the DZone community and get the full member experience.Join For Free
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
$ 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
│ ├── java
│ │ └── mrhaki
│ │ └── micronaut
│ │ └── Application.java
│ └── resources
│ ├── application.yml
│ └── logback.xml
9 directories, 3 files
Notice the tree structure reflects the structure for the package
When we invoke the
create-controller book command the generated files use the package name
$ 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
$ sed -E -i '' 's/(defaultPackage:) .*/\1 com\.mrhaki\.micronaut/g' micronaut-cli.yml
$ cat micronaut-cli.yml
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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.