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




Spring Resource Loader with example

Spring Resource Loader is very generic and easy to load resources directly as file, url or classpath and of any file types like text, media or image. By using getResource() we can implement single generic method for any file type. By implementing ResourceLoaderAware interface we can inject ResourceLoader object into the bean, since ResourceLoader is non-accessable from application context.

ResourceBeanConfig.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="resource" class="com.app.javadiscover.ResourceBean" />
   
</beans>


ResourceBean.java


package com.app.javadiscover;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class ResourceBean implements ResourceLoaderAware {
 private ResourceLoader resourceLoader;
 
 public void setResourceLoader(ResourceLoader resourceLoader) {
  this.resourceLoader = resourceLoader;
 }
  
 public Resource getResource(String location){
  return resourceLoader.getResource(location);
 }
}


LoadResource.java


package com.app.javadiscover;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;


public class LoadResource  {

 public static void main( String[] args )
    {
     ApplicationContext appContext =  new ClassPathXmlApplicationContext("ResourceBeanConfig.xml");

     Resource resource = appContext.getResource("classpath:ResourceBeanConfig.xml");
     
    try{
        InputStream iStream = resource.getInputStream();
          BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
         
          String text;
          
          while ((text = bReader.readLine()) != null) {
             System.out.println(text);
          } 
          bReader.close();
         
     }catch(IOException e){
      e.printStackTrace();
     }
     
    }
}


OUTPUT:

Spring Resource Loader with example


In above example we have used classpath to load xml file and to print line by line. Similar way we can use file and url resource loader as like below.


     Resource resource = appContext.getResource("file:C:\\javadiscover.xml");


     Resource resource = appContext.getResource("url:http://textfiles.com");


Sending email using embedded Image in Java

In our earlier tutorial we have how to send email using Java Code. As same way in this tutorial lets see how to send email using embedded image. By using javax.mail API we can achieve this by creating 2 MimeBodyPart instance for attaching image and to add HTML body text. In this below example lets see step by step to set SMTP server details and to message body with embedded image.


import java.io.IOException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class SendMail {

 public void emailWithEmbeddedImage() {

  try {

   final String from = "sender@gmail.com";
   final String password = "senderpassword";
   
   String toAddress = "to@gmail.com";
   String ccAddress ="cc@gmail.com";
   String bccAddress = "bcc@gmail.com";
   String name = "Job";
   
   // JavaMail session object
   Session session;

   // The JavaMail message object
   Message mesg;

   //SMTP server properties 
   Properties properties = new Properties();
   properties.put("mail.smtp.host", "smtp.gmail.com");
   properties.put("mail.smtp.port", 587);
   properties.put("mail.smtp.auth", "true");
   properties.put("mail.smtp.starttls.enable", "true");

   // authenticate sender username and password 
   Authenticator auth = new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(from, password);
    }
   };

   // initialize session object
   session = Session.getInstance(properties, auth);
   session.setDebug(false);

   // initialize message object
   mesg = new MimeMessage(session);

   // from Address
   mesg.setFrom(new InternetAddress(from));

   // Email Addresses
   InternetAddress toAdd = new InternetAddress(toAddress);
   InternetAddress ccAdd = new InternetAddress(ccAddress);
   InternetAddress bccAdd = new InternetAddress(bccAddress);

   mesg.addRecipient(Message.RecipientType.TO, toAdd);
   mesg.addRecipient(Message.RecipientType.CC, ccAdd);
   mesg.addRecipient(Message.RecipientType.BCC, bccAdd);

   // email Subject
   mesg.setSubject("Visitor Pass");

   // message body.
   Multipart mp = new MimeMultipart("related");

   String cid = "qr";

   MimeBodyPart pixPart = new MimeBodyPart();
   pixPart.attachFile("C:\\image.png");
   pixPart.setContentID("<" + cid + ">");
   pixPart.setDisposition(MimeBodyPart.INLINE);

   MimeBodyPart textPart = new MimeBodyPart();
   textPart.setText("<html>" + "Hello " + name + ", <br> "
     + "Please find your visiting QR code <br> "
     + "<div><img src=\"cid:" + cid
     + "\" /></div></html>" + "Thanks & Regards, <br> "
     + "Bill</html>", "US-ASCII", "html");

   // Attach text and image to message body
   mp.addBodyPart(textPart);
   mp.addBodyPart(pixPart);

   // Setting message content
   mesg.setContent(mp);

   // Send mail
   Transport.send(mesg);

  } catch (MessagingException e) {
   System.err.println(e);
   e.printStackTrace(System.err);
  } catch (IOException e) {
   System.err.println(e);
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  
  new SendMail().emailWithEmbeddedImage();
  
 }
}

OUTPUT:

Sending Email using embedded Image in Java

Here QR code image embedded with email and shown sample screen shot as output. 

Generate QR Code using Java

 
QR code (Quick Response Code) is the trademark for a type of matrix bar-code, first designed for the automotive industry in Japan. A QR code consists of black modules (square dots) arranged in a square grid on a white background, which can be read by an imaging device (such as a camera, scanner, etc.) and processed using Reed–Solomon error correction until the image can be appropriately interpreted. The required data are then extracted from patterns that are present in both horizontal and vertical components of the image.
Now lets see simple Java Code to generate QR code by using qrgen API

GenerateQRCode.java


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQRCode {

 public static void main(String[] args) {
  new GenerateQRCode().generateQRImage("sdfhjkjhrf23khsdfkh#@Wersdfcsdfsdf24r4sdf");
 }

 
 public void generateQRImage(String qrCode){
  
  try {
   
   ByteArrayOutputStream out = QRCode.from(qrCode).withSize(250, 250).to(ImageType.PNG).stream();

   FileOutputStream fout = new FileOutputStream(new File("C://"+qrCode+".png"));
            
            fout.write(out.toByteArray());
 
            fout.flush();
            fout.close();
            
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
  
 }
}


OUTPUT:

Generate QR Code using Java

Spring Boot + Restful Web Service + Spring Security

When we talk about Spring Boot (Simplifying Spring for Everyone) makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files). Now lets see simple example with combination of Spring Boot and Spring Restful Web Service which includes spring security for all our services or API's.
Spring Boot + Restful Web Service + Spring Security



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.javadiscover</groupId>
 <artifactId>springbootdemo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>springbootdemo</name>
 <description>Demo project for Spring Boot</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>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.7</java.version>
 </properties>

 <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>


ServletInitializer.java


package com.app.javadiscover;

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(SpringbootdemoApplication.class);
 }
}


SpringbootdemoApplication.java


package com.app.javadiscover;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}


MyController.java


package com.app.javadiscover.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class MyController {

 @RequestMapping(value="/sayhello/{name}", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<String> helloController(@PathVariable String name){
  
  String sayHello = "Hello "+name + " :)";
  
  return new ResponseEntity<String>(sayHello, HttpStatus.OK);
 } 
}


application.properties


security.user.password=springsecuritypassword


Spring Boot + Restful Web Service + Spring Security


OUTPUT:

Hello Java Discover - Spring Boot + Restful Web Service + Spring Security


Please download complete project from this link.