Niche IT Skills Hub

Learn About Java Frameworks, Data Science and Application Development with Examples

Sunday, 8 October 2017

Static Content in Spring Boot

No comments :
In this section we are going to talk about static content. CSS files, JavaScript, Images come in the category of static content. By default spring boot serve static content from a directory called “static” in the class path but there is a way to override these locations if you need to. There’s an important thing to remember, don’t use the src/main/webapp directory, if your application is going to be packaged as a jar, although, this directory is a common standard, it will only work with war packaging.
Now I want to introduce you to a term called “WebJars”. WebJars are easily manage the client-side dependencies in JVM-based web applications. You can use JVM-based build tools like maven, gradle etc.., to download your client-side dependencies (eg: Jquery, bootstrap etc..,). The really good thing about this is managing client-side dependencies can be a big pain and that’s why there are build tools out there for javascript dependencies like bower.
Now let’s see how to use static resources in our spring boot application. Go ahead and open spring tool suite and create a demo application using spring initializr by selecting web facet. Now create few folders to store static content (HTML,CSS, Images & JS) in "src/main/resources/static" path. Please see the below project structure for reference:

The only java code I have in the above project is main application file. If we run this project we will see a blank error page because there are no controllers in the project and we haven't configured any request mappings for the default "/" url. So, I've added home.html file to our static folder and we can load this file in the browser with the url "http://localhost:8090/home.html" (port number 8080 may differ in your case). In the above project, main.css file contains styling for our application and main.js file contains java script code. All manually downloaded external libraries (jquery, bootstrap, angular js etc..,) are placed in the folder named libraries (you can follow your own naming styles). I have linked all these files in our home.html file. See below code for reference:
<!DOCTYPE html>
<html>
<head>
 <title>My HTML Code</title>
 <link href="css/main.css" rel="stylesheet"/>
 <script src="js/main.js" type="application/javascript"></script>
 <script src="libraries/jquery-3.2.1.min.js" type="application/javascript"></script>
</head>
<body>
 Some Html code goes here...!
</body>
</html>
I think many of you already know how to include JS and CSS files in HTML file. We need to use link tag for including CSS file and script tag for including JS file. Let's see how to include bootstrap css file using WebJars. Go to WebJars (https://www.webjars.org/) website and copy the maven dependency of bootstrap. You can select version also over there. See below snapshot for reference:
Now add this dependency in you pom.xml and build the project. Now if you look into your Maven Dependencies, you will find bootstrap-version.jar. See below snapshot for reference:
Now include the files you want into your html file. You have to mention the path starting from webjars. See the below code for reference:
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
Congratulations! you have successfully learnt how to use Static Content and WebJars
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

@Profile Annotation in Spring Boot

No comments :
In this section we are going to see the usage of @profile annotation. If you are hearing the term profile for the first time, then I recommend to see our tutorial on "Spring Profile"Firstly, we need to add the names of the active profiles to  "spring.profiles.active" property in application.properties. You can give multiple profile names to this property by separating them by  a ", (comma)". Now add the below property to application.properties.
 spring.profiles.active=dev

Now create a simple POJO class of your own with constructors, getters and setters. I have created the below one:
package com.example.demo;

public class DataSource {
 private int portNumber;
 private String serverUrl;
 public DataSource(int portNumber, String serverUrl) {
  this.portNumber = portNumber;
  this.serverUrl = serverUrl;
 }
 public String getServerUrl() {
  return serverUrl;
 }
 public void setServerUrl(String serverUrl) {
  this.serverUrl = serverUrl;
 }
 public int getPortNumber() {
  return portNumber;
 }
 public void setPortNumber(int portNumber) {
  this.portNumber = portNumber;
 }
 @Override
 public String toString() {
  return "DataSource [portNumber=" + portNumber + ", server=" + serverUrl + "]";
 }
}
Now create a configuration class using @Configuration annotation. Create beans inside of the configuration class using @Bean annotation. Also, you can set a name to your bean by passing a name to @Bean annotation. See the below code for reference:
package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
public class DataSourceConfiguration {
 @Bean("dataSource")
 @Profile("dev")
 DataSource devDataSource() {
  return new DataSource(7070, "www.dev-data-source.com");
 } 
 @Bean("dataSource")
 @Profile("qa")
 DataSource qaDataSource() {
  return new DataSource(8080, "www.qa-data-source.com");
 } 
 @Bean("dataSource")
 @Profile("prod")
 DataSource prodDataSource() {
  return new DataSource(9090, "www.prod-data-source.com");
 }
}
If you observe the above configuration class, we have three profiles with names dev, qa and prod. Since we said to spring boot that active profile is dev, it will create a data source bean which has profile name as dev.
To test this I have changed main application class a bit. Please follow the below code:
package com.example.demo;

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

@SpringBootApplication
public class ProfileAnnotationDemoApplication {

 public static void main(String[] args) {
  ApplicationContext context = SpringApplication.run(ProfileAnnotationDemoApplication.class, args);
  System.out.println(context.getBean("dataSource").toString());
 }
}

I hope you already know that SpringApplication.run method will return you the ApplicationContext, So i have created a reference to it. Now I used getBean() method to print the output on the console. The bean name that we have used in the configuration class is passed to getBean() method and whatever toString() method in DataSource bean returns is printed on the console. Now run the application and see the output in the console, It should print the portNumber and serverUrl of profile dev. Try playing with this by changing the active profile in the application.properties file.
Congratulations! you have successfully learnt how to use @Profile annotation.
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

Saturday, 7 October 2017

Spring Profiles

No comments :
In this section we are going to look at Spring Profiles. "Spring Profiles" provides a way to segregate parts of your application configuration and make it available only in certain environments. You can easily imagine a scenario where you do development of an application on a local machine and then push to other environments like testing or production. You probably have one set of configuration for a data source on your local machine, that look way different in QA and production. Let’s see exactly how profiles works. Go ahead and open spring tool suite and create a demo application using spring initializr by selecting web facet. Firstly, we need to add the names of profiles to  "spring.profiles.active" property in application.properties. You can give multiple profile names to this property by separating them by  a ", (comma)". Now add the below property to application.properties.
 spring.profiles.active=dev
Now create application-dev.properties file and add few properties into it. Here the file name convention is very simple to follow, the name should start with 'application', end with the 'profile name (dev in our case)' by separating them with '-'   See below code for reference.
app.message=You are in development mode.
app.url=www.nicheitskillshub-dev.com
Create application-qa.properties file with same properties but with different values. See below code for reference:
app.message=You are in testing mode.
app.url=www.nicheitskillshub-qa.com
Create application-prod.properties file with same properties but with different values. See below code for reference:
app.message=You are in production mode.
app.url=www.nicheitskillshub.com
If you want, you can create more files like this. Spring boot will check for the active profile in application.properities file and pull only those property values for you.
Now create a rest controller to access the property values. See the below code for reference:
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProfileDemoController {
 
 @Value("${spring.profiles.active}")
 private String activeProfile;
 
 @Value("${app.message}")
 private String message;
 
 @Value("${app.url}")
 private String url;
 
 @RequestMapping("/")
 public String welcomeToProfiles(){ 
  return activeProfile + " " + message + " " + url;
 }
}
If you observe we have passed property names to @Value annotation, so that the property value can be stored in the variable of a JAVA class. Run the server and open localhost, then you should be able to see the values that are coming from our active profile, in our case it is dev, so spring boot takes values for application-dev.properties file. Try playing with this by changing the active profile in application.properties.
Congratulations! you have successfully learnt how to use profiles.
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

@ConfigurationProperties Annotation in Spring Boot

No comments :
In this section we will look at a problem that may come up during development. There are times when you have entire classes that have properties that will need to be loaded from the configuration. You could easily add @value annotation to each property and map it to a configuration property. But that begins to become very tedious and very error prone. Spring boot introduced a @ConfigurationProperties annotation that allows us to map properties to POJO class. Now let's see how to make use of @ConfigurationProperties annotation to map properties to a POJO class. Go ahead and open spring tool suite and create a demo application using spring initializr by selecting web facet. To make use of @ConfigurationProperties annotation we need to add the following dependency in pom.xml.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency> 
To work with @ConfigurationProperties annotation, we need to add @EnableConfigurationProperties in the main application class. Please the below code for reference.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties
public class ConfigurationPropertiesDemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(ConfigurationPropertiesDemoApplication.class, args);
	}
} 
Now create a application.yml file or add some properties to existing application.properties file. If your willing to create YAML file, please see the below code for reference:
myDetails:
  father-name: Sai
  mother-name: Padma
  wifeName: Someone
  sonName: Shiva
Now create a new class with @Service annotation and create few variables with names matching to the properties that are added in the YAML or properties file. We need to add the @ConfigurationProperties to this class and pass the prefix that we used in creation of properties in YAML/property files. Please the below class for reference:
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
@Service
@ConfigurationProperties(prefix = "myDetails")
public class MyPersonalDetails {
	private String fatherName;
	private String motherName;
	private String wifeName;
	private String sonName;
	public String getFatherName() {
		return fatherName;
	}
	public void setFatherName(String fatherName) {
		this.fatherName = fatherName;
	}
	public String getMotherName() {
		return motherName;
	}
	public void setMotherName(String motherName) {
		this.motherName = motherName;
	}
	public String getWifeName() {
		return wifeName;
	}
	public void setWifeName(String wifeName) {
		this.wifeName = wifeName;
	}
	public String getSonName() {
		return sonName;
	}
	public void setSonName(String sonName) {
		this.sonName = sonName;
	}
	@Override
	public String toString() {
		return "MyPersonalDetails [fatherName=" + fatherName + ", motherName=" + motherName + ", wifeName=" + wifeName
				+ ", sonName=" + sonName + "]";
	}	
}
If you observe the above class we have used camel case variable names but in the property file we have few properties where words are separated by '-'. Don't worry about, it will mix and match those for you when it does the binding, which is really awesome!
Now let's create a restcontroller and inject the above class to it. Please see the below code:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyDetailsController {
	private MyPersonalDetails myPersonalDetails;
	@Autowired
	public MyDetailsController(MyPersonalDetails myPersonalDetails) {
		this.myPersonalDetails = myPersonalDetails;
	}
	@RequestMapping("/")
	public String getMyDetails() {
		return myPersonalDetails.toString();
	}
}
So, If you run the server and open localhost, then you should be able to see the values from properties or YAML files on your browser.
Congratulations! you have successfully learnt how to use @ConfigurationProperties Annotation
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

Externalized Configuration in Spring Boot

No comments :
In this section we are going to talk about externalized configuration. Spring boot allows you to externalize your configuration, so you can work with the same application code in different environments. You can use property files, YAML files, environment variables and even command line arguments to externalize configuration. Property values can be injected directly into your beans using the @Value annotation.
Application.properties: A Properties file is nothing more than a key-value pair configuration file. When we create a basic spring boot project using spring initializr, it creates an applications.properties file for us and it is located in “src/main/resources”. By default, spring boot search for your external configuration file (application.properties) in the following locations and add them to spring environment:
·        · The package '/config' in classpath.
·        · The classpath root.
·        · The '/config' subdirectory of the current directory.
·        · The current directory.
YAML Files:  You can use YAML files as an alternative to properties. YAML is a superset of JSON and it is very convenient format for specifying configuration data. If you created project using spring initializr, the spring application class will automatically support YAML. I like YAML configuration more than properties file just because they are more concise. You can choose anyone (YAML or properties) or even both. Spring will merge both properties and YAML files. But, if same key is configured in both, the properties file is going to win. Please remember that the extension of YAML files is .yml
Example of YAML Document:
environments:
    dev:
      url: http://www.nicheitskillshub.dev.com
      name: Developer Mode of Niche IT Skills Hub
    prod:
      url: http://www.nicheitskillshub.com
      name: Niche IT Skills Hub
The above YAML file would be transformed into these properties:
environments.dev.url=http://www.nicheitskillshub.dev.com
environments.dev.name=Developer Mode of Niche IT Skills Hub
environments.dev.url=http://www.nicheitskillshub.com
environments.dev.name=Niche IT Skills Hub
Now it is the time to do hands on these two files. Go ahead and open spring tool suite and create a demo application using spring initializr by selecting web facet. Now, go to “src/main/resources” path and open the application.properties file and add the following properties (You can add your own properties):
home.personal.father.name = Sai
home.personal.mother.name = Padma
Now create application.yml (YAML file) file in “src/main/resources” path and add the following in it:
home:
  personal:
    wife:
      name: Someone
    son:
      name: Shiva  
Now create a rest controller and make use of the above .properties and .yml files. See the below code for reference:
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
 @Value("${home.personal.father.name}")
 private String fatherName;
 
 @Value("${home.personal.mother.name}")
 private String motherName;
 
 @Value("${home.personal.wife.name}")
 private String wifeName;
 
 @Value("${home.personal.son.name}")
 private String sonName;
 
 @RequestMapping("/")
 public String welcomeToHome(){
  StringBuffer details = new StringBuffer();
  details.append("Father Name: ").append(fatherName).append("<br/>");
  details.append("Mother Name: ").append(motherName).append("<br/>");
  details.append("Wife Name: ").append(wifeName).append("<br/>");
  details.append("Son Name: ").append(sonName);
  return details.toString();
 }
} 
We need to pass the property name into @Value annotation. If you start the server and open localhost then you should be able to see the values from properties and YAML files on the browser.
Congratulations! you have successfully learnt how to use properties and YAML files.
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

Recent Posts on Spring Boot