dineshonjava

Spring Boot with Spring MVC Application

Spring Boot reduced lots of spring configuration and kick o fast development. Spring Boot offers a new paradigm for developing Spring applications with minimal friction. With Spring Boot, you’ll be able to develop Spring applications with more agility and be able to focus on addressing your application’s functionality needs with minimal.

Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat, Jetty, or Undertow. Most web applications will use the spring-boot-starter-web module to get up and running quickly.
Spring Web MVC framework
MVC stands for Model, View, Controller. The MVC design pattern is probably the most popular design pattern used when writing code to generate dynamic web content.
  • Model refers to a data model, or some type of data structure.
  • The view layer, in Java frequently a JSP. This will take data from the Model and render the view.
  • Spring MVC lets you create special @Controller or @RestController beans to handle incoming HTTP requests. Methods in your controller are mapped to HTTP using @RequestMapping annotations.


Spring MVC auto-configuration
Spring Boot provides auto-configuration for Spring MVC. There are following features for auto-configuration for Spring MVC.
  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars. By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method. Any resources with a path in /webjars/** will be served from jar files if they are packaged in the Webjars format.
  • Automatic registration of Converter, GenericConverter, Formatter beans.
  • Support for HttpMessageConverters. Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses.
  • Automatic registration of MessageCodesResolver. Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver
  • Static index.html support. If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html in any of your locations on startup, it will be the home page of the application.
  • Custom Favicon support.
  • Automatic use of a ConfigurableWebBindingInitializer bean. Spring MVC uses a WebBindingInitializer to initialize a WebDataBinder for a particular request. If you create your own ConfigurableWebBindingInitializer @Bean, Spring Boot will automatically configure Spring MVC to use it.
  • When you’re using one of these templating engines (thymeleaf, freemarker, velocity, Groovy etc.) with the default configuration, your templates will be picked up automatically from src/main/resources/templates.
  • Error Handling Spring Boot provides an /error mapping by default that handles all errors in a sensible way, and it is registered as a ‘global’ error page in the servlet container. For machine clients it will produce a JSON response with details of the error, the HTTP status and the exception message. For browser clients there is a ‘whitelabel’ error view that renders the same data in HTML format. If you want to display a custom HTML error page for a given status code, you add a file to an /error folder. Error pages can either be static HTML (i.e. added under any of the static resource folders) or built using templates. The name of the file should be the exact status code or a series mask.
  • Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most developers will simply use the appropriate ‘Starter’ to obtain a fully configured instance. By default the embedded server will listen for HTTP requests on port 8080.
  • Any Servlet, Filter or Servlet *Listener instance that is a Spring bean will be registered with the embedded container. This can be particularly convenient if you want to refer to a value from your application.properties during configuration.
  • By default, if the context contains only a single Servlet it will be mapped to /. In the case of multiple Servlet beans the bean name will be used as a path prefix. Filters will map to /*.
  • EmbeddedWebApplicationContext The EmbeddedWebApplicationContext is a special type of WebApplicationContext that bootstraps itself by searching for a single EmbeddedServletContainerFactory bean.
Customizing embedded servlet containers
Common servlet container settings can be configured using Spring Environment properties. Usually you would define the properties in your application.properties file.
  • Network settings: listen port for incoming HTTP requests (server.port), interface address to bind to server.address, etc.
  • Session settings: whether the session is persistent (server.session.persistence), session timeout (server.session.timeout), location of session data (server.session.store-dir) and session-cookie configuration (server.session.cookie.*).
  • Error management: location of the error page (server.error.path), etc.


Logging Configuration in Spring Boot

Hello friends!!! Once again we are going to discuss very important topic about spring boot configuration. We always curious about defining tacking or logs basis things own way. Like Pizza organization provide the tracking about the ordered pizza what is the current status of pizza. Still we supposed to see more detailed status like information about pizza base or how to make pizza and also supposed there no problem happens in preparing the pizza.
Logging is not the core requirement for any business application but we cannot ignore it because logging is very important part for any application for tracking information about application and helpful for developer in debugging the application. In some applications developers use synchronous logging which can impact the application’s performance. Logging libraries like Logback, Log4j2 provide async logging.

Spring Boot provides support for logging and uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.
By default, if you use the ‘Starters’, Logback will be used for logging. Here we are going to use default logging by Spring Boot.

Default Logging Format in Spring Boot
The default logs look like as below

2016-07-24 20:31:45.280  INFO 10220 --- [           main] c.d.SpringBootHelloWorldApplication      : Starting SpringBootHelloWorldApplication on NODTBSL206AG with PID 10220 (started by Dinesh.Rajput in D:\personal data\spring-boot-workspace\SpringBootHelloWorld)
2016-07-24 20:31:45.286  INFO 10220 --- [           main] c.d.SpringBootHelloWorldApplication      : No active profile set, falling back to default profiles: default
2016-07-24 20:31:45.502  INFO 10220 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1809907: startup date [Sun Jul 24 20:31:45 IST 2016]; root of context hierarchy
2016-07-24 20:31:48.201  INFO 10220 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-07-24 20:31:48.226  INFO 10220 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-07-24 20:31:48.228  INFO 10220 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.3
2016-07-24 20:31:48.485  INFO 10220 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-07-24 20:31:48.485  INFO 10220 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2993 ms

The following items are output:

  • Date and Time: Millisecond precision and easily sort able.
  • Log Level: ERROR, WARN, INFO, DEBUG or TRACE.
  • Process ID.
  • A --- Separator to distinguish the start of actual log messages.
  • Thread name: Enclosed in square brackets (may be truncated for console output).
  • Logger name: This is usually the source class name (often abbreviated).
The log message.

The default log level configured by logback is DEBUG i.e any messages logged at ERROR, WARN, INFO and DEBUG get printed on the console.

Create Spring Boot Maven Project
Let’s create a Maven Spring Boot project for customizing logging configuration.
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.dineshonjava</groupId>
 <artifactId>SpringBootHelloWorld</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>SpringBootHelloWorld project for Spring Boot</description>

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

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

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </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>

In above pom.xml we do not need to add the logging dependency explicitly because dependency spring-boot-starter includes the dependencies for logging spring-boot-starter-logging. The spring-boot-starter-logging includes SLF4J and logback dependencies with appropriate SLF4J wrappers for other logging libraries.

Now let’s see Class file where we have logs message
package com.dineshonjava;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringBootHelloWorldApplication {
 
private static final Logger logger = LoggerFactory.getLogger(SpringBootHelloWorldApplication.class);
 

@RequestMapping("/")
    String home() {
        return "Hello World!";
    }
 
public static void main(String[] args) {
    SpringApplication.run(SpringBootHelloWorldApplication.class, args);
    logger.error("Message logged at ERROR level");
    logger.warn("Message logged at WARN level");
    logger.info("Message logged at INFO level");
    logger.debug("Message logged at DEBUG level");
}
}


There are following logs look like after running above class.
2016-07-24 20:57:40.828 ERROR 3024 --- [           main] c.d.SpringBootHelloWorldApplication      : Message logged at ERROR level
2016-07-24 20:57:40.828  WARN 3024 --- [           main] c.d.SpringBootHelloWorldApplication      : Message logged at WARN level
2016-07-24 20:57:40.828  INFO 3024 --- [           main] c.d.SpringBootHelloWorldApplication      : Message logged at INFO level

Customizing default Configuration for Logging:
By adding logback.xml file to the application we can override the default logging configuration providing by the Spring Boot. This file place in the classpath (src/main/resources) of the application for Spring Boot to pick the custom configuration.
Logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- Log message format -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
      </pattern>
    </encoder>
  </appender>

  <!-- Setting the root level of logging to INFO -->
  <root level="info">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

There are following things we have note:

  • We are using a appender STDOUT using ConsoleAppender which prints to the console
  • We are giving pattern to the appender to build the log message
  • Set up a root logger which logs any message above INFO level using the STDOUT appender


There are following logs look like after running this application.
21:14:46.352 [main] ERROR c.d.SpringBootHelloWorldApplication - Message logged at ERROR level
21:14:46.352 [main] WARN  c.d.SpringBootHelloWorldApplication - Message logged at WARN level
21:14:46.352 [main] INFO  c.d.SpringBootHelloWorldApplication - Message logged at INFO level

We have to note here in above logs there is no DEBUG logs printed.

Printing Logs into a File:
By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition to the console output you need to set a logging.file or logging.path property in your application.properties.

There are following cases for logging property:

  • If No logging.path and No logging.file then Console only logging.
  • If No logging.path and Specify logging.file then writes to the specified log file. Names can be an exact location or relative to the current directory.
  • If Specify logging.path and No logging.file then writes spring.log to the specified directory. Names can be an exact location or relative to the current directory.

Log files will rotate when they reach 10 Mb and as with console output, ERROR, WARN and INFO level messages are logged by default.

Now let’s see the following changes we are made in the logback.xml as below
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- Log message format -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <!-- Need appender to write to file -->
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <!-- Name of the file where the log messages are written -->
    <file>MySpringBootApp.log</file>
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <logger name="com.dineshonjava.service" level="warn">
    <appender-ref ref="FILE" />
  </logger>

  <!-- Setting the root level of logging to INFO -->
  <root level="info">
    <appender-ref ref="FILE" />
  </root>
</configuration>

Here we are introducing one more file “HelloService.java” for logging purpose as below:
package com.dineshonjava.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloService {
private Logger logger = LoggerFactory.getLogger(HelloService.class);
public void service(){
  logger.info("Message at INFO level from HelloService.service()");
  logger.warn("Message at WARN level from HelloService.service()");
}
}

Now running the application will redirect all the log messages to the file MySpringBootApp.log present in the current directory.


Custom log configuration
The various logging systems can be activated by including the appropriate libraries on the classpath, and further customized by providing a suitable configuration file in the root of the classpath, or in a location specified by the Spring Environment property logging.config.

Depending on your logging system, the following files will be loaded:
  1. Logback -> logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy
  2. Log4j2 -> log4j2-spring.xml or log4j2.xml
  3. JDK (Java Util Logging) -> logging.properties


There are following properties we can use for custom log configuration
  1. logging.file -> Used in default log configuration if defined for logging file name.
  2. logging.path -> Used in default log configuration if defined for logging file path of directory.
  3. logging.pattern.console -> The log pattern to use on the console.
  4. logging.pattern.file -> The log pattern to use in a file.
  5. logging.pattern.level -> The format to use to render the log level.
  6. logging.exception-conversion-word -> The conversion word that’s used when logging exceptions.


Summary
Here we have seen enough things about how to use the logging processes in Spring Boot application. First we have see about the default logging support in the Spring Boot applications and then we have made it how to override them by modifying the logback.xml file. And also we have discussed list of all properties those we have used to customize the logging configuration in the spring boot application.

Happy Spring Boot Learning!!!


Customizing Spring Boot Auto Configuration

Hello friends!!! Once again lets us discuss one of the important topics for spring boot is customizing spring boot autoconfiguration. As all we know that  Freedom of choice is an awesome thing. If you like PIZZA so you have many choices to select your favorite PIZZA like PAN PIZZA, PIZZA with cheese bust, pizza with different different tops yummy :). Now friends please come to our discussion, here we’re going to look at two ways to influence auto-configuration: explicit configuration overrides and fine-grained configuration with properties.
Overriding auto-configured beans
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. If you can get what you need without it then why would you do extra work, writing and maintaining extra configuration code, but sometimes there are many cases Spring Boot auto configuration is not good enough. For example one of the cases is when you’re applying security to your application. Security in your application is one of major concern so it is not single fit for all because there are decisions around application security that Spring Boot has no business making for you even though Spring Boot provides auto configuration for some basic spring security things.

For securing the application:
Just adding Spring Security Starter to add spring security auto configuration to the application. In gradle add following line to build.gradle file.
compile("org.springframework.boot:spring-boot-starter-security")
In Maven add following dependency for spring security starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
That’s it! Rebuild your application and run it. It’s now a secure web application! The security starter adds Spring Security to the application’s classpath. With Spring Security on the classpath, auto-configuration kicks in and a very basic Spring Security setup is created. When open this application browser basic authentication is needed then user name is “user” and password is printed in logs.

Custom security configuration in the application
Basic default configuration probably is not fit for your application because unlike authentication page and password is printed in the logs. That is why you will prefer customized security configuration in the application. For overriding default spring boot auto configuration just writing explicit XML based or Java based configuration in the application this means writing a configuration class that extends WebSecurityConfigurerAdapter.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserRepository userRepository;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/").access("hasRole(ADMIN)")
        .antMatchers("/**").permitAll()
        .and()
        .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error=true");
  }
        @Override
       protected void configure(
          AuthenticationManagerBuilder auth) throws Exception {
     auth
       .userDetailsService(new UserDetailsService() {
       @Override
       public UserDetails loadUserByUsername(String username)
                  throws UsernameNotFoundException {
           return userRepository.findUserName(username);
       }
    });
  }
}

SecurityConfig is a very basic Spring Security configuration. Even so, it does a lot of what we need to customize security of the application.

Configuring with external properties
Spring Boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, Java system properties, JNDI and command-line arguments to externalize configuration. Spring Boot offers over 300 properties for auto configuration of beans in the application.

Let’s see one of property when you start the application one banner is printed at log screen. So you can disable that banner by setting property spring.main.show-banner to false.

There are following ways to setting up this property when we run the application

Command Line Parameters:
$ java -jar myapp-0.0.1-SNAPSHOT.jar --spring.main.show-banner=false

Setting in “application.properties” property file:
spring.main.show-banner=false

Create a YAML file named “application.yml”:
spring:
     main:
         show-banner: false

Setting property as an environment variable:
$ export spring_main_show_banner=false

Note: the use of underscores instead of periods and dashes, as required for environment variable names.

There are, in fact, several ways to set properties for a Spring Boot application. Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:
  1. @TestPropertySource annotations on your tests.
  2. Command line arguments.
  3. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  4. ServletConfig init parameters.
  5. ServletContext init parameters.
  6. JNDI attributes from java:comp/env.
  7. Java System properties (System.getProperties()).
  8. OS environment variables.
  9. A RandomValuePropertySource that only has properties in random.*.
  10. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  11. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  12. Application properties outside of your packaged jar (application.properties and YAML variants).
  13. Application properties packaged inside your jar (application.properties and YAML variants).
  14. @PropertySource annotations on your @Configuration classes.
  15. Default properties (specified using SpringApplication.setDefaultProperties)
As for the application.properties and application.yml files, they can reside in any of four locations:
  1. Externally, in a /config subdirectory of the directory from which the application is run
  2. Externally, in the directory from which the application is run
  3. Internally, in a package named “config
  4. Internally, at the root of the classpath

Again, this list is in order of precedence. That is, an application.properties file in a /config subdirectory will override the same properties set in an application.properties file in the application’s classpath.

Also, I’ve found that if you have both application.properties and application.yml side by side at the same level of precedence, properties in application.yml will override those in application.properties.

Auto-configuration
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. You should only ever add one @EnableAutoConfiguration annotation.

Gradually replacing auto-configuration
Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource bean, the default embedded database support will back away.

Disabling specific auto-configuration
1. DISABLING TEMPLATE CACHING
Thymeleaf templates are cached by default that is why changes is never replicate unless you restart the application. You can disable Thymeleaf template caching by setting spring.thymeleaf.cache to false.
Using command-line argument:
$ java -jar myapp-0.0.1-SNAPSHOT.jar --spring.thymeleaf.cache=false
Using application.yml file
spring:
     thymeleaf:
          cache: false
You’ll want to make sure that this application.yml file doesn’t follow the application into production.
Using environment variable:
$ export spring_thymeleaf_cache=false
Others template caching can be turned off for Spring Boot’s other supported template options by setting these properties:
  • spring.freemarker.cache (Freemarker)
  • spring.groovy.template.cache (Groovy templates)
  • spring.velocity.cache (Velocity)
2. CONFIGURING THE EMBEDDED SERVER
By default embedded server for spring boot application is tomcat with port 8080. It is fine in case of single application running but it will be become problem in case run multiple applications simultaneously. If all of the applications try to start a Tomcat server on the same port, there’ll be port collisions starting with the second application.

So to prevent these collisions of port we need to do is set the server.port property.

If this is a one-time change, it’s easy enough to do this as a command-line argument:
$ java -jar myapp-0.0.1-SNAPSHOT.jar --server.port=8181
For permanent port change use application.yml:
server:
     port: 8000
3. CONFIGURING LOGGING
By default, Spring Boot configures logging via Logback (http://logback.qos.ch) to log to the console at INFO level.

For Maven builds, you can exclude Logback by excluding the default logging starter transitively resolved by the root starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
In Gradle, it’s easiest to place the exclusion under the configurations section:
configurations {
all*.exclude group:'org.springframework.boot',
module:'spring-boot-starter-logging'
}
With the default logging starter excluded, you can now include the starter for the logging implementation you’d rather use. With a Maven build you can add Log4j like this:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
In a Gradle build you can add Log4j like this:
compile("org.springframework.boot:spring-boot-starter-log4j")
For full control over the logging configuration, you can create a logback.xml file at the root of the classpath (in src/main/resources). Here’s an example of a simple logback.xml file you might use:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="root" level="INFO"/>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
To set the logging levels, you create properties that are prefixed with logging.level, followed by the name of the logger for which you want to set the logging level.
application.yml:
logging:
    level:
        root: WARN
        org:
             springframework:
                      security: DEBUG


Now suppose that you want to write the log entries to a file named MyApp.log at /opt/logs/. The logging.path and logging.file properties can help with that:
logging:
     path: /opt/logs/
     file: MyApp.log
     level:
         root: WARN
     org:
        springframework:
              security: DEBUG
By default, the log files will rotate once they hit 10 megabytes in size.

application.properties:
logging.path=/opt/logs/
logging.file=MyApp.log
logging.level.root=WARN
logging.level.root.org.springframework.security=DEBUG
You can also change name of logger configuration file name i.e. you can change name of file logback.xml to log-config.xml by setting the property logging.config in property file or YML file.
logging:
    config:
        classpath:log-config.xml

4. CONFIGURING A DATA SOURCE
application.yml: if you’re using a MySQL database, your application.yml file might look like this
spring:
     datasource:
           url: jdbc:mysql://localhost/dojdb
           username: root
          password: root

Specify driver name for database with property spring.datasource
.driver-class-name property as follows
spring:
     datasource:
           url: jdbc:mysql://localhost/dojdb
           username: root
          password: root
         driver-class-name: com.mysql.jdbc.Driver
Using JNDI for DataSource:
By using property spring.datasource.jndi-name
spring:
      datasource:
            jndi-name: java:/comp/env/jdbc/dojDBDS


Type-safe Configuration Properties
If you are working with multiple properties or your data is hierarchical in nature then sometimes it may be problem in configuration properties. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application.

For example:
@Component
@ConfigurationProperties(prefix="database")
public class DatabaseSettings {

    private String dbname;

    private String dburl;

    // ... getters and setters

}
The @EnableConfigurationProperties annotation is automatically applied to your project so that any beans annotated with @ConfigurationProperties will be configured from the Environment properties. The @ConfigurationProperties annotation won’t work unless you’ve enabled it by adding @EnableConfigurationProperties in one of your Spring configuration classes. This style of configuration works particularly well with the SpringApplication external YAML configuration:
application.yml
database:
    dbname: dojdb
    dburl: jdbc:mysql//192.168.1.1:3309/dojdb

# additional configuration as required
To work with @ConfigurationProperties beans you can just inject them in the same way as any other bean.
@Service
public class UserService {
    @Autowired
    private DatabaseSettings connection;
     //...
    @PostConstruct
    public void openConnection() {
        Server server = new Server();
        this.connection.configure(server);
    }
}
It is also possible to shortcut the registration of @ConfigurationProperties bean definitions by simply listing the properties classes directly in the @EnableConfigurationProperties annotation:
@Configuration
@EnableConfigurationProperties(DatabaseSettings.class)
public class DBConfiguration {
}
Using @ConfigurationProperties for outside beans:
We can use @ConfigurationProperties for beans which either outside from the application or not in your control. Let‘s see below
@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
    ...
}
Any property defined with the foo prefix will be mapped onto that FooComponent bean in a similar manner as the DatabaseSettings example above.

Note: Biding Property in Spring Boot
It’s also worth noting that Spring Boot’s property resolver is clever enough to treat camel-cased properties as interchangeable with similarly named properties with hyphens or underscores. In other words, a property named database.dbName is equivalent to both database.db_name and database.db-name. And also DATABASE_DB_NAME as environment variable in OS.

@ConfigurationProperties Validation
Spring Boot will attempt to validate external configuration, by default using JSR-303 (if it is on the classpath). You can simply add JSR-303 javax.validation constraint annotations to your @ConfigurationProperties class:
@Component
@ConfigurationProperties(prefix="database")
public class DatabaseSettings {
    @NotNull
    private String dbName;
    @NotNull
    private String dbUrl;
    // ... getters and setters
}


Configuring with profiles
When applications are deployed to different runtime environments, there are usually some configuration details that will differ. The details of a database connection, for instance, are likely different in a development environment than in a quality assurance environment, and different still in a production environment.
@Configuration
@Profile("production")
public class ProductionConfiguration {
    // ...
}
The @Profile annotation used here requires that the “production” profile be active at runtime for this configuration to be applied. If the “production” profile isn’t active, this configuration will be ignored and applied any default auto configuration.

Activate profiles:
Profiles can be activated by setting the spring.profiles.active property using any of the means available for setting any other configuration property. For example, you could activate the “production” profile by running the application at the command line like this:
$ java -jar MyApp-0.0.1-SNAPSHOT.jar -- spring.profiles.active=production
Or you can add the spring.profiles.active property to application.yml:
spring:
    profiles:
        active: production
Profile-specific properties:
If you’re using application.properties to express configuration properties, you can provide profile-specific properties by creating additional properties files named with the pattern “application-{profile}.properties”. Profile-specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.

For Example the development configuration would be in a file named application-development.properties and contain properties for verbose, console written logging:
logging.level.root=DEBUG
But for production, application-production.properties would configure logging to be at WARN level and higher and to write to a log file:
logging.path=/opt/logs/
logging.file=MyApp.log
logging.level.root=WARN
Multi-profile YAML documents:
You can specify multiple profile-specific YAML documents in a single file by using a spring.profiles key to indicate when the document applies. For example:
logging:
    level:
        root: INFO
---
spring:
    profiles: development
logging:
     level:
         root: DEBUG
---
spring:
      profiles: production
logging:
      path: /opt/
      file: MyApp.log
     level:
          root: WARN
As you can see, this application.yml file is divided into three sections by a set of triple hyphens (---). The second and third sections each specify a value for spring .profiles. This property indicates which profile each section’s properties apply to.

The properties defined in the middle section apply to development because it sets spring.profiles to “development”. Similarly, the last section has spring.profiles set to “production”, making it applicable when the “production” profile is active.

The first section, on the other hand, doesn’t specify a value for spring.profiles. Therefore, its properties are common to all profiles or are defaults if the active profile doesn’t otherwise have the properties set.

Customizing error pages
Spring Boot offers this “whitelabel” error page by default as part of auto-configuration. The default error handler that’s auto-configured by Spring Boot looks for a view whose name is “error”. The easiest way to customize the error page is to create a custom view that will resolve for a view named “error”.

Ultimately this depends on the view resolvers in place when the error view is being resolved. This includes
  • Any bean that implements Spring’s View interface and has a bean ID of “error” (resolved by Spring’s BeanNameViewResolver)
  • A Thymeleaf template named “error.html” if Thymeleaf is configured
  • A FreeMarker template named “error.ftl” if FreeMarker is configured
  • A Velocity template named “error.vm” if Velocity is configured
  • A JSP template named “error.jsp” if using JSP views

Summary
Spring Boot Auto configuration do almost configuration for your application. When autoconfiguration doesn’t fit your needs, Spring Boot allows you to override and fine-tune the configuration it provides.


Happy Spring Boot Learning!!!


Developing your first Spring Boot application Hello World

Hello friends!!! Let’s develop a simple “Hello World!” web application in Java that highlights some of Spring Boot’s key features. We’ll use Maven to build this project since most IDEs support it.

We are using intializr to quick create project so we can choose either via one of following Initializr interfaces to create web application project structure to initiate.

Here we are going to use web interface to create project structure for “Hello World” web application. As below figure I have created

Developing your first Spring Boot application Hello World

Once the project has been created, you should have a project structure similar to that shown in figure below.
Spring-boot-hello-world

Examining a newly initialized Spring Boot project
Now let’s slow down and take a closer look at what’s contained in the initial project. First thing to noticed in the project structure follow the layout of Maven or Gradle project That is, the main application code is placed in the src/main/java branch of the directory tree, resources are placed in the src/main/ resources branch, and test code is placed in the src/test/java branch At this point we don’t have any test resources, but if we did we’d put them in src/test/resources.

Let see auto generated files in deeper:
Pom.xml: The Maven build specification
This is the recipe that will be used to build your project.
<?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.dineshonjava</groupId>
 <artifactId>SpringBootHelloWorld</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>SpringBootHelloWorld project for Spring Boot</description>

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

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

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </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>
 
 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
 </repositories>
 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </pluginRepository>
 </pluginRepositories>

</project>

Spring Boot provides a number of “Starters” that make easy to add jars to your classpath. Our sample application has already used spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults.

SpringBootHelloWorldApplication.java
The application’s bootstrap class and primary Spring configuration class

package com.dineshonjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringBootHelloWorldApplication {
 
 @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
 
 public static void main(String[] args) {
  SpringApplication.run(SpringBootHelloWorldApplication.class, args);
 }
}


The @RestController and @RequestMapping annotations
@RestController is known as a stereotype annotation. The @RequestMapping annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

The @SpringBootApplication annotation
The @SpringBootApplication enables Spring component-scanning and Spring Boot auto-configuration. In fact, @SpringBootApplication combines three other useful annotations:
  • Spring’s @Configuration—Designates a class as a configuration class using Spring’s Java-based configuration. Although we won’t be writing a lot of configuration in this tutorial, we’ll favor Java-based configuration over XML configuration when we do.
  • Spring’s @ComponentScan—Enables component-scanning so that the web controller classes and other components you write will be automatically discovered and registered as beans in the Spring application context. Here we’ll write a simple Spring MVC controller that will be annotated with @RestController so that component-scanning can find it.
  • Spring Boot’s @EnableAutoConfiguration— This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
application.properties—A place to configure application and Spring Boot properties. The application.properties file given to you by the Initializr is initially empty. In fact, this file is completely optional, so you could remove it completely without impacting the application.

Suppose we are adding following line to this property file
server.port=1208

With this line, you’re configuring the embedded Tomcat server to listen on port 1208 instead of the default port 8080.

SpringBootHelloWorldApplicationTests.java—A basic integration test class
package com.dineshonjava;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootHelloWorldApplicationTests {

 @Test
 public void contextLoads() {
 }

}


In a typical Spring integration test, you’d annotate the test class with @Context- Configuration to specify how the test should load the Spring application context. But in order to take full advantage of Spring Boot magic, the @SpringApplication- Configuration annotation should be used instead.

The “main” method:
The final part of our application is the main method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server.

Running the example
Type mvn spring-boot:run from the root project directory to start the application:
.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.4.0.RC1)

2016-07-14 08:54:35.959  INFO 12868 --- [           main] c.d.SpringBootHelloWorldApplication      : Starting SpringBootHelloWorldApplication on NODTBSL206AG with PID 12868 (started by Dinesh.Rajput in D:\personal data\spring-boot-workspace\SpringBootHelloWorld)
2016-07-14 08:54:35.961  INFO 12868 --- [           main] c.d.SpringBootHelloWorldApplication      : No active profile set, falling back to default profiles: default
2016-07-14 08:54:36.096  INFO 12868 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1809907: startup date [Thu Jul 14 08:54:36 IST 2016]; root of context hierarchy

2016-07-14 08:54:39.630  INFO 12868 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)

If you open a web browser to localhost:8080 you should see the following output:

Spring-boot-hello-world

Creating an executable jar
Let’s finish our example by creating a completely self-contained executable jar file that we could ruSn in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.

To create an executable jar we need to add the spring-boot-maven-plugin to our pom.xml. Insert the following lines just below the dependencies section:
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


Save your pom.xml and run mvn package from the command line:

D:\personal data\spring-boot-workspace\SpringBootHelloWorld>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootHelloWorld 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SpringBoot
HelloWorld ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.5.1:compile (default-compile) @ SpringBootHel
loWorld ---

[INFO] Nothing to compile - all classes are up to date

If you look in the target directory you should see SpringBootHelloWorld -0.0.1-SNAPSHOT.jar.

To run that application, use the java -jar command:

$ java -jar target/ SpringBootHelloWorld -0.0.1-SNAPSHOT.jar

/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.4.0.RC1)

2016-07-14 08:54:35.959  INFO 12868 --- [           main] c.d.SpringBootHelloWorldApplication      : Starting SpringBootHelloWorldApplication on NODTBSL206AG with PID 12868 (started by Dinesh.Rajput in D:\personal data\spring-boot-workspace\SpringBootHelloWorld)
2016-07-14 08:54:35.961  INFO 12868 --- [           main] c.d.SpringBootHelloWorldApplication      : No active profile set, falling back to default profiles: default
2016-07-14 08:54:36.096  INFO 12868 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1809907: startup date [Thu Jul 14 08:54:36 IST 2016]; root of context hierarchy
2016-07-14 08:54:39.630  INFO 12868 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)



Summary
By taking advantage of Spring Boot starter dependencies and auto-configuration, you can more quickly and easily develop Spring applications. Starter dependencies help you focus on the type of functionality your application needs rather than on the specific libraries and versions that provide that functionality. Meanwhile, auto-configuration frees you from the boilerplate configuration that is common among Spring applications without Spring Boot.



Happy Spring Boot Learning!!! :-)


Installing Spring Boot

You can use Spring Boot in the same way as any standard Java library. Simply include the appropriate spring-boot-*.jar files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor; and there is nothing special about a Spring Boot application, so you can run and debug as you would any other Java program.

You can also add simply all spring boot jar files to classpath of application but we are recommending use any build tools (Maven/Gradle) for dependencies management.

Maven Installation:
Spring Boot is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at How to Install Maven in Windows. Ubuntu users can run sudo apt-get install maven.
Spring Boot dependencies use the org.springframework.boot groupId. Typically your Maven POM file will inherit from the spring-boot-starter-parent project and declare dependencies to one or more “Starters”.

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.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.BUILD-SNAPSHOT</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <!-- Add Spring repositories -->
    <!-- (you don't need this if you are using a .RELEASE version) -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>
</project>

Gradle installation:

Spring Boot is compatible with Gradle 1.12 or above. If you don’t already have Gradle installed you can follow the instructions at How to Install Gradle. Spring Boot dependencies can be declared using the org.springframework.boot group. Typically your project will declare dependencies to one or more “Starters”. Spring Boot provides a useful Gradle plugin that can be used to simplify dependency declarations and to create executable jars.

build.gradle
buildscript {
    repositories {
        jcenter()
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.BUILD-SNAPSHOT")
    }
}

apply plugin: 'java'
apply plugin: 'spring-boot'

jar {
    baseName = 'myproject'
    version =  '0.0.1-SNAPSHOT'
}

repositories {
    jcenter()
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}


Installing the Spring Boot CLI:
The Spring Boot CLI is a command line tool that can be used if you want to quickly prototype with Spring. It allows you to run Groovy scripts, which means that you have a familiar Java-like syntax, without so much boilerplate code.

You can follow the instructions at Spring Boot CLI installation to setup the Spring Boot CLI.


In the coming tutorial we will create the first Spring Boot Application.


Happy Spring Boot Learning :)