Spring + @PropertySource with @Value and Environment

 
In Spring we can configure our application properties in property file and by @PropertySource annotation we can configure externalized configuration file. Those property values can be read by using @Value annotation or by using Environment class.
In below lets see simple example how to use @PropertySource to read property file and to fetch those values using @Value and Environment class. Simple example that we need to serve static resources from different locations to configure in Spring and that too separate location for images and separate for text files etc., Those locations are configured in "myConfig.properties" file.

myConfig.properties

staticresourceloader.imageFileLocation.path:file:C:\\images\\

staticresourceloader.txtFileLocation.path:file:C:\\txtfiles\\



Reading values using @Value annotation

package com.app.staticresourceloader;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@ComponentScan
@EnableAutoConfiguration
@PropertySource("classpath:myConfig.properties")
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter  {

 @Value("${staticresourceloader.imageFileLocation.path}")
    private String staticImageFilePath;
 
 @Value("${staticresourceloader.txtFileLocation.path}")
    private String staticTxtFilePath;
 
 public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        
    }
    
 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
  System.out.println("IMAGE FILE PATH :::: "+staticImageFilePath);
  System.out.println("TEXT FILE PATH  :::: "+staticTxtFilePath);
  
  registry.addResourceHandler("/api/image/**").addResourceLocations(staticImageFilePath);
        registry.addResourceHandler("/api/txt/**").addResourceLocations(staticTxtFilePath);
        
    }   
}



Reading values using Environment

package com.app.staticresourceloader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@ComponentScan
@EnableAutoConfiguration
@PropertySource("classpath:myConfig.properties")
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter  {

 @Autowired
 private Environment pathDetails;
 
 public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        
    }
    
 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
  
  String imagePath = pathDetails.getProperty("staticresourceloader.imageFileLocation.path");
  String txtPath = pathDetails.getProperty("staticresourceloader.txtFileLocation.path");
  
  System.out.println("IMAGE FILE PATH :::: "+imagePath);
  System.out.println("TEXT FILE PATH  :::: "+txtPath);
  
  registry.addResourceHandler("/api/image/**").addResourceLocations(imagePath);
        registry.addResourceHandler("/api/txt/**").addResourceLocations(txtPath);
        
    }   
}


OUTPUT:

Spring + @PropertySource with @Value and Environment

Spring Boot + Spring Security + Serve static resources from different locations

In Spring we can configure static resources such as  images, js, and, css files from specific locations under web application root, the classpath, and other locations. Even we can configure multiple locations to server different type of file.
An implementation of WebMvcConfigurer interface in WebMvcConfigurerAdapter abstract class with empty methods allowing sub-classes to override only the methods they're interested in. To achieve and serve static resources from different locations we need to extend WebMvcConfigurerAdapter class and need to @Override addResourceHandlers() method in our Application class.
Lets simple example to serve static resources like images and text files from different locations.
Here in this example we are loading images and text files from different locations like

  • images from C://images 
  • text files from C://txtfiles

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.app</groupId>
 <artifactId>staticresourceloader</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>staticresourceloader</name>
 <description>staticresourceloader project</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.2.5.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

  <dependencies>
  
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-ws</artifactId>
  </dependency>
  
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>
 
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>


application.properties

security.user.password=Efhj34tGVW

staticresourceloader.imageFileLocation.path:file:C:\\images\\

staticresourceloader.txtFileLocation.path:file:C:\\txtfiles\\


Application.java

package com.app.staticresourceloader;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter  {

 @Value("${staticresourceloader.imageFileLocation.path}")
    private String staticImageFilePath;
 
 @Value("${staticresourceloader.txtFileLocation.path}")
    private String staticTxtFilePath;
 
 public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/api/image/**").addResourceLocations(staticImageFilePath);
        registry.addResourceHandler("/api/txt/**").addResourceLocations(staticTxtFilePath);
    }    
}


ServletInitializer.java

package com.app.staticresourceloader;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  return application.sources(Application.class);
 } 
}


MyController.java

package com.app.staticresourceloader;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class MyController {

 @Value("${staticresourceloader.imageFileLocation.path}")
    private String staticImageFilePath;
 
 @Value("${staticresourceloader.txtFileLocation.path}")
    private String staticTxtFilePath;
 
 
 @RequestMapping(value="/api/getImageList", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<Collection<String>> getImageList(){
  
  Collection<String> fileList = fileList(staticImageFilePath, "image");
  
  return new ResponseEntity<Collection<String>>(fileList, HttpStatus.OK);
 } 
 
 


        @RequestMapping(value="/api/getTxtList", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<Collection<String>> getTxtFileList(){
  
  Collection<String> fileList = fileList(staticTxtFilePath, "txt");
  
  return new ResponseEntity<Collection<String>>(fileList, HttpStatus.OK);
 } 
 
 


        public Collection<String> fileList(String folderPath, String type) {
  
  File directory = new File(folderPath.replace("file:", ""));
  File[] fList = directory.listFiles();
  
  Collection<String> list = new ArrayList<String>();
  
  for (File file : fList) {
   
   list.add("http://localhost:8080/api/"+type+"/"+file.getName());
  }  
  return list;
 } 
}


Spring Boot + Spring Security + Serve static resources from different locations



OUTPUT:

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations