What is Bean Factory in Spring?

- A Bean Factory is like a factory class that contains collections of beans. The Bean Factory holds bean definition of multiple beans within itself and then instantiates the bean when asked by client.
- Bean Factory is actual representation of the Spring IOC container that is responsible for containing and managing the configured beans.

Different Spring Bean Scope.

1. singleton : Return a single bean instance per Spring IOC container.
2. prototype : Return a new bean instance each time when requested.
3. request : Return a single bean instance per HTTP request.
4. session : Return a single bean instance per HTTP session.
5. global session : Return a single bean instance per global HTTP session and only valid when used in portlet context.

How you will decide when to use prototype scope and when singleton scope bean?

- You should use the prototype scope for all beans that are stateful and the singleton scope should be used for stateless beans.

What is Aspect Oriented Programming (AOP) in Spring? how advice work with AOP.

Basically Aspect oriented programming complements object oriented programming by providing another way of programming model structure.

In addition to classes, AOP gives you aspect, which enables modularization of concerns such as Transaction management or logging and can be separated out from the application business logic of the code (these kinds of concerns are termed as crosscutting concerns). AOP supports separating application business logic from System services.

In Spring AOP, 4 type of advices are supported :

  • Before advice ? Run before the method execution
  • After returning advice ? Run after the method returns a result
  • After throwing advice ? Run after the method throws an exception
  • Around advice ? Run around the method execution, combine all three advices above.
  • springaop

    Create a simple customer service class with printCustomerName, printAddress and printThrowException methods

    package com.javacodepoint.customer.services;
    
    public class CustomerService {
    	private String name;
    	private String address;
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setAddress(String address) {
    		this.address = address;
    	}
    
    	public void printCustomerName() {
    		System.out.println("Name of Customer : " + this.name);
    	}
    
    	public void printAddress() {
    		System.out.println("Address of Customer : " + this.address);
    	}
    
    	public void printThrowException() {
    		throw new IllegalArgumentException();
    	}
    
    }
    

    Spring-javacodepoint-Customer.xml bean configuration file

    <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-2.5.xsd">
    
    	<bean id="customerService" class="com.javacodepoint.customer.services.CustomerService">
    		<property name="name" value="Ravi kumar verma" />
    		<property name="url" value="Patiala Punjab" />
    	</bean>
    
    	<bean id="AOPThrowExceptionBean" class="com.javacodepoint.aop.AOPThrowException" />
    
    	<bean id="customerServiceBean"
                     class="org.springframework.aop.framework.ProxyFactoryBean">
    
    		<property name="target" ref="customerService" />
    
    		<property name="interceptorNames">
    			<list>
    				<value>AOPThrowExceptionBean</value>
    			</list>
    		</property>
    	</bean>
    </beans>

    AOPMainApp.java file to run

    package com.javacodepoint.mainApp;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.javacodepoint.customer.services.CustomerService;
    
    public class AOPMainApp {
    	public static void main(String[] args) {
    		ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "Spring-javacodepoint-Customer.xml" });
    
    		CustomerService customer = (CustomerService) appContext.getBean("customerServiceBean");
    
    		System.out.println("----------------------------------------------------------------");
    		customer.printCustomerName();
    		System.out.println("----------------------------------------------------------------");
    		customer.printAddress();
    		System.out.println("----------------------------------------------------------------");
    		try {
    			customer.printThrowException();
    		} catch (Exception e) {
    			//e.printStackTrace();
    		}
    
    	}
    }
    

    Spring AOP advice

    before advice: It will execute before the method execution. Create a class which implements MethodBeforeAdvice interface.

    package com.javacodepoint.aop;
    
    import java.lang.reflect.Method;
    import org.springframework.aop.MethodBeforeAdvice;
    
    public class AOPBeforeMethod implements MethodBeforeAdvice {
    	public void before(Method method, Object[] args, Object target)
    			throws Throwable {
    		System.out.println("Javacodepoint BeforeMethod : Before method Javacodepoint!");
    	}
    }
    

    after advice : It will execute after the method is returned a result. Create a class which implements AfterReturningAdvice interface

    package com.javacodepoint.aop;
    
    import java.lang.reflect.Method;
    import org.springframework.aop.AfterReturningAdvice;
    
    public class AOPAfterMethod implements AfterReturningAdvice {
    	public void afterReturning(Object returnValue, Method method,
    			Object[] args, Object target) throws Throwable {
    		System.out.println("HijackAfterMethod : After method hijacked!");
    	}
    }
    

    After throwing advice : It will execute after the method throws an exception. Create a class which implements ThrowsAdvice interface, and create a afterThrowing method to hijack the IllegalArgumentException exception.

    package com.javacodepoint.aop;
    
    import org.springframework.aop.ThrowsAdvice;
    
    public class AOPThrowException implements ThrowsAdvice {
    	public void afterThrowing(IllegalArgumentException e) throws Throwable {
    		System.out.println(" Javacodepoint ThrowException : Throw exception Javacodepoint!");
    	}
    }
    

    Around advice : It combines all three advices above, and execute during method execution. Create a class which implements MethodInterceptor interface. You have to call the ?methodInvocation.proceed();? to proceed on the original method execution, else the original method will not execute

    package com.javacodepoint.aop;
    
    import java.util.Arrays;
    
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    public class AOPAroundMethod implements MethodInterceptor {
    	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    
    		System.out.println("name of Method : "	+ methodInvocation.getMethod().getName());
    		System.out.println("arguments of Method : "	+ Arrays.toString(methodInvocation.getArguments()));
    
    		// same with MethodBeforeAdvice
    		System.out.println("Javacodepoint AOPAroundMethod : Before method Javacodepoint!");
    
    		try {
    			// proceed to original method call
    			Object result = methodInvocation.proceed();
    
    			// same with AfterReturningAdvice
    			System.out.println("Javacodepoint AOPAroundMethod : Before after Javacodepoint!");
    
    			return result;
    
    		} catch (IllegalArgumentException e) {
    			// same with ThrowsAdvice
    			System.out
    					.println("Javacodepoint AOPAroundMethod : Throw exception Javacodepoint!");
    			throw e;
    		}
    	}
    }
    

    springaop

    output

    Jul 20, 2017 1:28:21 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4edde6e5: display name [org.springframework.context.support.ClassPathXmlApplicationContext@4edde6e5]; startup date [Thu Jul 20 01:28:21 IST 2017]; root of context hierarchy
    Jul 20, 2017 1:28:21 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [Spring-javacodepoint-Customer.xml]
    Jul 20, 2017 1:28:21 AM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
    INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@4edde6e5]: org.springframework.beans.factory.support.DefaultListableBeanFactory@4aa8f0b4
    Jul 20, 2017 1:28:21 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4aa8f0b4: defining beans [customerService,AOPAroundMethodBean,customerServiceBean]; root of factory hierarchy
    ----------------------------------------------------------------
    name of Method : printCustomerName
    arguments of Method : []
    Javacodepoint AOPAroundMethod : Before method Javacodepoint!
    Name of Customer : Ravi kumar Verma
    Javacodepoint AOPAroundMethod : Before after Javacodepoint!
    ----------------------------------------------------------------
    name of Method : printAddress
    arguments of Method : []
    Javacodepoint AOPAroundMethod : Before method Javacodepoint!
    Address of Customer : Patiala Punjab
    Javacodepoint AOPAroundMethod : Before after Javacodepoint!
    ----------------------------------------------------------------
    name of Method : printThrowException
    arguments of Method : []
    Javacodepoint AOPAroundMethod : Before method Javacodepoint!
    Javacodepoint AOPAroundMethod : Throw exception Javacodepoint!
    
    

    What is IOC or Dependency Injection?

    The basic concept of IOC (Dependency of Injection) is that you do not create your objects but describe how they should be created.

    - You don?t directly connect your component and services together in code but describe which services are needed by which component in configuration file.

    - You just need to describe the dependency, the Spring container is then responsible for hooking it all up.

    When to use Dependency Injections?

    There are different scenarios where you Dependency Injections are useful.

    - You need to inject configuration data into one or more component.

    - You need to inject the same dependency into multiple components.

    - You need to inject different implementation of the same dependency.

    - You need to inject the same implementation in different configuration.

    - You need some of the services provided by container.

    When you should not use Dependency Injection?

    There were scenarios where you don?t need dependency injections e.g.

    - You will never need a different implementation.

    - You will never need different configurations.

    How you will decide when to use prototype scope and when singleton scope bean?

    You should use the prototype scope for all beans that are stateful and the singleton scope should be used for stateless beans.

    What are the different types of IOC?

    There are three types of dependency Injection:

    1. Constructor Injection :

    - Dependencies are provided as a constructor parameter.

    2. Setter Injection :

    Dependencies are assigned through setter method.

    3. Interface Injection :

    Injection is done through an interface and not supported in spring framework..

    Differentiate between BeanFactory and ApplicationContext in spring.

    - With ApplicationContext more than one config files are possible while only one config file or .xml file is possible with BeanFactory.

    - ApplicationContext publishes events to beans that are registered as listeners while BeanFactory doesnot support this

    - ApplicationContext support internationalization messages, application life-cycle events, validation and many enterprise services like JNDI access, EJB integration, remoting etc. while BeanFactory doesnot support any of these.

    What is the difference between singleton and prototype bean?

    Mainly it is the scope of a beans which defines their existence on the application

    Singleton : It means single bean definition to a single object instance per Spring IOC container.

    Prototype : It means a single bean definition to any number of object instances.,

    What type of transaction Management Spring support?

    Spring supports two types of transaction management:

    1. Programmatic transaction management

    2. Declarative transaction management.

    When do you use programmatic and declarative transaction management?

    - Programmatic transaction management is used preferably when you have a small number of transactional operations.

    - Incase of large number of transactional operations it is better to use declarative transaction management.

    What is IOC and How it's works

    - IOC stands for Inversion of Control pattern.

    - It is also called as dependency injection.

    - This concept says that you do not create your objects but describe how they should be created.

    - Similarly, you do not directly connect your components and services together in code but describe which services are needed by which components in a configuration file.

    - A container then hooks them all up.

    The main goal of spring framework to make application loosely coupled, in which Dependency Injection gives help.

    Dependency Injection is the process where objects define their dependency that how they work with another objects.

    IOC(Inversion of control)

    IOC Container is responsible for manage the Spring Bean i.e creating the bean, life cycle of bean, configuring the bean according to metadata either it take from java code or xml file where dependency objects written. IOC Container written in two package like org.springframework.bean and org.springframework.context. There are two interface work with IOC liek BeanFactory and ApplicationContext. BeanFactory only responsible for initializing the spring bean objects where ApplicationContext do all transactions and Aspect Oriented Programming.

    So , basically we say, ApplicationContext is better to use than BeanFactory.

    The following example of xmlBeanFactory

    <?xml version="1.0" encoding="UTF-8"?>
    <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="helloWorld" class="com.src.Spring.HelloSpringWorld">
    <name="HelloMessage" value="Hello Spring world!"/>
    </bean>
    </beans>
    

    HelloSpringWorld.java

    package com.src.Spring.HelloSpringWorld
    
    public class HelloSpringWorld {
    	private String HelloMessage;
    	public void setMessage(String HelloMessage){ 
    		this.HelloMessage = HelloMessage;
    		} 
    	public void getMessage()
    	{
    		System.out.println("Printing the message : " + HelloMessage); 
    	} 
    
    
    }
    
    

    creating Spring Bean

    package com.src.Spring.HelloSpringWorld
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource; 
    
    public class HelloSpringWorldMain 
    {
    	public static void main(String[] args)
    	{ 
    		XmlBeanFactory factory = new XmlBeanFactory (newClassPathResource("Beans.xml")); 
    		HelloSpringWorld obj = (HelloSpringWorld) factory.getBean("HelloMessage"); 
    		obj.getMessage(); 
    		} 
    	}
    
    

    In above code, xmlBeanFactory laods the xml metadata and assembled on basis of bean request and last getMessage() find the result

    The following example of ApplicationContext

    It will do similar to xmlBeanFactory like laod the bean and wire with objects. some more things do applicationContext like AOP, transactions, get Text message from properties files and push this to interested listners.

  • FileSystemXmlApplicationContext - This implementation loads the definitions of the beans from an XML file. It is required to provide the full path of the XML bean configuration file to the constructor.
  • ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. However, it is not required to provide the full path of the XML file. It does require you to set CLASSPATH properly because this container will look for bean configuration XML file in the specified CLASSPATH.
  • XmlWebApplicationContext: This container loads the XML file with definitions of all beans from within a web application.
  • <?xml version="1.0" encoding="UTF-8"?>
    <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="helloWorld" class="com.src.Spring.HelloSpringWorld">
    <name="HelloMessage" value="Hello Spring world!"/>
    </bean>
    </beans>
    

    HelloSpringWorld.java

    package com.src.Spring.HelloSpringWorld
    
    public class HelloSpringWorld {
    	private String HelloMessage;
    	public void setMessage(String HelloMessage){ 
    		this.HelloMessage = HelloMessage;
    		} 
    	public void getMessage()
    	{
    		System.out.println("Printing the message : " + HelloMessage); 
    	} 
    
    
    }
    
    

    FileSystemXmlApplicationContext

    package com.src.Spring.HelloSpringWorld
    public static void main(String[] args) {
    	ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Ravispace/workspace/HelloSpringWorld/src/Beans.xml"); 
    	HelloSpringWorld obj = (HelloSpringWorld) context.getBean("HelloMessage"); 
    	obj.getMessage(); 
    	}
    
    

    What are the benefits of IOC?

    The main benefits of IOC or dependency injections are :

    1. It minimizes the amount of code in your application.

    2. It makes your application easy to test as it doesnot require any singletons or JNDI lookup mechanisms in your unit test cases.

    3. Loose coupling is promoted with minimal effort and least intrusive mechanism.

    4. IOC containers support eager instantiation and lazy loading of services.

    What is Bean Wiring?

    Bean wiring means creating associations between application components i.e. beans within the spring container.

    How do you access Hibernate using Spring ?

    There are two ways to Spring?s Hibernate integration:

    1. By Inversion of Control with a HibernateTemplate and Callback.

    2. By extending HibernateDaoSupport and Applying an AOP Interceptor.

    How would you integrate Spring and Hibernate using HibernateDaoSupport?

    This can be done through Spring?s SessionFactory called LocalSessionFactory. The steps in integration process are:

    1. Configure the Hibernate SessionFactory.

    2. Extend your DAO Implementation from HibernateDaoSupport.

    3. Wire in Transaction Support with AOP.

    What are the various transaction manager implementations in Spring?

    1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources.

    2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.

    3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.

    4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions.

    What is Auto Wiring in Spring?

    - The Auto-wiring in spring framework can be performed by configuring in xml and Spring Auto-Wiring with Annotation @Autowired.

    - Auto-wiring beans with xml configuration: In Spring framework, you can wire beans automatically with auto-wiring feature. To enable auto-wiring just define the ?autowire? attribute in tag.

    What are Advice, Aspect, Join-point and point cut in spring?

    Aspect : An aspect is a subprogram which is associated with specific property of a program (Example separating logging code from the main program). An aspect is functionality or feature that cross cuts over object. AOP increase modularity of a program.

    Join-Point : A join point is a point used in spring AOP framework to represent a method execution. It always point during execution of program, method or exception. A join point is basically an opportunity within the code to apply aspect.

    Point Cut : In AOP a point cut is a set of many join points where an advice can execute. A chunk of code (known as Advice) associated with join point get executed.

    What are the different types of Advice?

    There are different types of Advice.

    Before Advice :

    The advice which executed before a join point called before advice. The before advice does not have the ability to prevent the execution flow proceeding at the join point (unless it throws an exception).

    After Return Advice :

    The advice which executed after a join point completed normally without any exception.

    Around Advice :

    It is responsible for choosing whether to proceeds to the join point or shortcut the advised method execution by returning its own return value or throwing an exception. This is most powerful kind of advice. With Around advice you can perform custom behavior before and after method execution.

    After Throwing Advice :

    The advice executed when a method throws an exception.

    After (finally) Advice :

    The advice is executed when program exits the join points either normally or by throwing an exception.

    What is Weaving in Spring?

    Weaving is the process of linking aspect with other application types or object to create an advised object. This can be performed at compile time, runtime and load time. In spring framework weaving is performed at runtime

    What is AOP Proxy?

    AOP proxy is an object to implement the aspect contracts (advice method executions and so on). The AOP proxy is object is created by the AOP framework. In spring framework AOP proxy is JDK dynamic proxy or CGLIB proxy.

    What is front controller in Spring MVC?

    The Front Controller is basically a type of Design pattern which are being implemented in different framework (e.g. Struts and Spring MVC etc.). - In Spring MVC DispatcherServlet act as a Front Controller for the framework and responsible for intercepting every request and then dispatches/forwards request to appropriate controller. Configure the DispatcherServlet in the web.xml file of web application and request which we want to be handled by DispatcherServlet should be mapped using URL mapping.

    Difference between FileSystemResource and ClassPathResource.

    - In FileSystemResource you need to give the configuration file (i.e. spring-config.xml) relative to your project or the absolute location of the file.

    - In ClassPathResource spring looks for the file in the ClassPath so configuration (i.e. spring-config.xml) file should be included in the classpath. If spring-config.xml is in classpath, you can simply give the name of the file.

    Spring Boot

    Spring boot module

    Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can just run. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

    You can use Spring Boot to create Java applications that can be started using java -jar or more traditional war deployments. We also provide a command line tool that runs spring scripts.

    Our primary goals are:
  • Provide a radically faster and widely accessible getting started experience for all Spring development.
  • Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
  • Absolutely no code generation and no requirement for XML configuration.
  • Features of Spring Boot

    SpringApplication features

    Stratup Failure

    If your application fails to start, registered FailureAnalyzers get a chance to provide a dedicated error message and a concrete action to fix the problem. For instance if you start a web application on port 8080 and that port is already in use, you should see something similar to the following:

    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Embedded servlet container failed to start. Port 8080 was already in use.
    
    Action:
    
    Identify and stop the process that is listening on port 8080 or configure this application to listen on another port.
    

    Customizing Banner

    The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.charset (default is UTF-8). In addition to a text file, you can also add a banner.gif, banner.jpg or banner.png image file to your classpath, or set a banner.image.location property. Images will be converted into an ASCII art representation and printed above any text banner.

    Customizing SpringApplication

    If the SpringApplication defaults aren?t to your taste you can instead create a local instance and customize it. For example, to turn off the banner you would write:

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MySpringConfiguration.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }

    Fluent Builder API

    If you need to build an ApplicationContext hierarchy (multiple contexts with a parent/child relationship), or if you just prefer using a ?fluent? builder API, you can use the SpringApplicationBuilder.

    The SpringApplicationBuilder allows you to chain together multiple method calls, and includes parent and child methods that allow you to create a hierarchy.

    new SpringApplicationBuilder()
            .sources(Parent.class)
            .child(Application.class)
            .bannerMode(Banner.Mode.OFF)
            .run(args);
    

    Web Environment

    Admin Features

    Accessing application arguments

    Spring Session

    Spring Boot provides Spring Session auto-configuration for a wide range of stores:

  • JDBC
  • MongoDB
  • Redis
  • Hazelcast
  • HashMap
  • If Spring Session is available, you must choose the StoreType that you wish to use to store the sessions. For instance to use JDBC as backend store, you?d configure your application as follows:

    spring.session.store-type=jdbc
    System Requirements for Spring boot Spring Boot with Java 6 or 7, we generally recommend Java 8 if at all possible Spring Boot applications to any Servlet 3.0+ compatible container Required Jar spring-boot-*.jar Maven installation

    Spring Boot is compatible with Apache Maven 3.2 or above

    Here is a typical pom.xml file:

    
    
        4.0.0
    
        com.BootExample
        myproject
        0.0.1-SNAPSHOT
    
        
        
            org.springframework.boot
            spring-boot-starter-parent
            1.5.4.RELEASE
        
    
        
        
            
                org.springframework.boot
                spring-boot-starter-web
            
        
    
        
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                
            
        
    
    
    

    Gradle installation

    Spring Boot is compatible with Gradle 2 (2.9 or later) and Gradle 3

    Here is a typical build.gradle file:

    plugins {
        id org.springframework.boot version 1.5.4.RELEASE
        id java
    }
    
    
    jar {
        baseName = myproject
        version =  0.0.1-SNAPSHOT
    }
    
    repositories {
        jcenter()
    }
    
    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 don?t need to use the CLI to work with Spring Boot but it?s definitely the quickest way to get a Spring application off the ground.

    Writing the code

    import org.springframework.boot.*;
    import org.springframework.boot.autoconfigure.*;
    import org.springframework.stereotype.*;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @EnableAutoConfiguration
    public class Example {
    
        @RequestMapping("/")
        String home() {
            return "Hello World!";
        }
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Example.class, args);
        }
    
    }

    The @RestController and @RequestMapping annotations

    The first annotation on our Example class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code, and for Spring, that the class plays a specific role. In this case, our class is a web @Controller so Spring will consider it when handling incoming web requests.

    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 @EnableAutoConfiguration annotation

    The second class-level annotation is @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.

    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. We need to pass Example.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

    Starters

    Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.

    The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.

    What?s in a name
    
    All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of application. This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs allow you to search dependencies by name. For example, with the appropriate Eclipse or STS plugin installed, you can simply hit ctrl-space in the POM editor and type ?spring-boot-starter? for a complete list.
    
    As explained in the Creating your own starter section, third party starters should not start with spring-boot as it is reserved for official Spring Boot artifacts. A third-party starter for acme will be typically named acme-spring-boot-starter.
    

    Using the @SpringBootApplication annotation

    The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes:

    package com.example.myproject;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }

    Using YAML instead of Properties

    YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. The SpringApplication class will automatically support YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath.

    Loading YAML

    Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map

    For example, the following YAML document:

    environments:
        dev:
            url: http://dev.bar.com
            name: Developer Setup
        prod:
            url: http://foo.bar.com
            name: My Cool App
    

    Would be transformed into these properties:

    environments.dev.url=http://dev.bar.com
    environments.dev.name=Developer Setup
    environments.prod.url=http://foo.bar.com
    environments.prod.name=My Cool App
    

    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:

    server:
        address: 192.168.1.101
    ---
    spring:
        profiles: development
    server:
        address: 127.0.0.1
    ---
    spring:
        profiles: production
    server:
        address: 192.168.1.122
        address: 192.168.1.120

    Link
    Eng. Ravi Kumar Verma

    Simple and dept learning technology is very important part in software development. Same story has been implemented at this site, so learn and implement the inovative things, Thanks

    Ravi Kumar Verma