Following example shows how to inject ResourceLoader as a bean in our Spring application.
this is a my file content.
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import jakarta.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.nio.file.Files; @Component public class ClientBean { @Autowired private ResourceLoader resourceLoader; @PostConstruct public void init() throws IOException { Resource resource = resourceLoader.getResource("classpath:myFile.txt"); File file = resource.getFile(); String s = new String(Files.readAllBytes(file.toPath())); System.out.println(s); } }
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import java.io.IOException; @Configuration @ComponentScan public class InjectResourceLoaderExample { public static void main(String[] args) throws IOException { new AnnotationConfigApplicationContext(InjectResourceLoaderExample.class); } }
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.