7

I am migrating a tiny Spring Boot application to Micronaut 1.0.1 and I was wondering if there is an equivalent for org.springframework.core.io.Resource and their implementation such as ClasspathResource?

In Spring Boot I inject a resource into a service using its constructor.

@Service
public class MyService() {

    private final Resource resource;

    public MyService(Resource resource) { this.resource = resource; }
}

How can I do this in Micronaut?

@Singleton
public class MyService() {

    private final Resource resource;

    @Inject
    public MyService(Resource resource) { this.resource = resource; }
}
saw303
  • 8,051
  • 7
  • 50
  • 90

4 Answers4

10

In Micronaut you can use io.micronaut.core.io.ResourceLoader variants, such as io.micronaut.core.io.scan.ClassPathResourceLoader or io.micronaut.core.io.file.FileSystemResourceLoader. One option to get them is via io.micronaut.core.io.ResourceResolver:

ClassPathResourceLoader loader = new ResourceResolver().getLoader(ClassPathResourceLoader.class).get();
Optional<URL> resource = loader.getResource("classpath:foo/bar.txt");
3

I used io.micronaut.core.io.ResourceLoader. Wired through the constructor:

@Controller("root")
public class MyController {

    private final ResourceLoader loader;

    public MyController(ResourceLoader loader) {
        this.loader = loader;
    }

    @Get("/index")
    @Produces(MediaType.TEXT_HTML)
    public String greet() throws IOException {
        return new String(loader.getResourceAsStream("index.html").get().readAllBytes());
    }
}

path to my index.html: src/main/resources/index.html

ffmammadov
  • 31
  • 5
3

ResourceLoader works well but you can do better. In Micronaut you can use io.micronaut.core.io.Readable. It is roughly equivalent to Spring's Resource. You can also use Readable in ConfigurationProperties and thus bind your configuration yaml/properties directly to Readable properties:

micronaut:
  application:
    name: Demo
images:
  image-file: "classpath:images/bismarckia-nobilis.jpg"
  # image-file: "file:/path/to/images/bismarckia-nobilis.jpg"
  other-files:
    - "classpath:images/bismarckia-nobilis.jpg"
    - "classpath:images/bamboo.jpg"
    - "classpath:images/hibiscus.jpg"

I have created:

Gunnar Hillert
  • 578
  • 4
  • 11
2

You can do it this way

@Singleton
public class MyService {

    @Value("classpath:your-file.json")
    private Readable readable;
}

or

@Singleton
public class MyService {

    private final Readable readable;

    public MyService(@Value("classpath:your-file.json") Readable file) {
        this.readable = readable;
    }
}
LE GALL Benoît
  • 7,159
  • 1
  • 36
  • 48