"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Boot Internals Date : 29/03/2025 (Session - 15) _____________________________________________________________________________________________________________________________ Yesterday Session ================= * We discussed about Spring Boot Internals * Different annotations required to start of SpringBoot Application. @SpringBootApplication ======================= * It is main annotation for every Spring Boot Application. * It is used to simplify the configuration and bootstrapping of Spring-based applications. * The annotation combines three commonly used annotations: @SpringBootConfiguration, @ComponentScan, @EnableAutoConfiguration. @SpringBootConfiguration ======================== * It is specialized form of the @Configuration annotation specific to SpringBoot Application. * Indicates that the class is a configuration class, providing bean definitions and other Spring configurations. It allows you to define beans and their dependencies explicitly. NOTE ==== @Configuration is an Parent Annotation @SpringBootConfiguration is an Child Annotation * In Spring boot Application we can represent configuration class with help of either any one of above two annotations. @ComponentScan ============== * Scans the specified packages and automatically detects and registers beans within those packages. * It enables component scanning and auto-detection of Spring components, such as controllers, services, repositories, and other beans. @EnableAutoConfiguration ========================= * Enables Spring Boot's auto-configuration mechanism. It automatically configures various Spring components and third-party libraries based on the classpath dependencies and the defined configurations. This reduces the manual configuration required to set up a Spring application. Spring-boot-jdbc-starter >>>>>>> JdbcTemplate,NamedParameterJdbcTemplate Spring-boot-web-starter >>>>>>> DispatcherServlet,ViewResolver -------------------------------------------------------------------------------------------------------- IIQ) If we remove the @SpringBootApplication annotations on the main class what will happens ? --> Spring Boot Application will run successfully but we couldn't get the features of Spring Boot such as Autoconfiguration,componentscan etc., --------------------------------------------------------------------------------------------------------- IIQ) @Configuration VS @SpringBootConfiguration Annotation ? -> 1) Both of these Annotations are functional one and same to mark the Java Class as Configuration classes. 2) @Configuration can be used only in Spring Applications but we can't use @SpringBootConfiguration in Spring Applications. @SpringBootConfiguration & @Configuration can be used in Spring Boot Applications. --------------------------------------------------------------------------------------------------------- Spring Boot Banner ================== * Banner is nothing but whenever spring boot application is started we can see Spring banner in the console. * As a programmer we can have control to disable the banner by using configuration and programmatical approach. * As a programmer we can have control to customize the banner of an Spring Boot Application. * We can have option to disable the banner of spring boot application we need to do add the below configuration application.properties ====================== spring.main.banner-mode=off * For the above entry we have three values i.e.,console(Default),log,off console >>>> Printing the Spring banner on the console. log >>>>> Printing the Spring banner in to log file. off >>>> Disabling the Spring banner for Spring Boot Application. * We can disable the banner of the Spring boot application through programatically with the help of below code SpringApplication app = new SpringApplication(Application.class); app.setBannerMode(Banner.Mode.OFF); app.run(args); * We can customize the banner of the Spring boot application from "Spring" to "Ashok IT" with below URL to generate banner and download the banner file into our machine and place into src/main/resource folder of our project. https://devops.datenkollektiv.de/banner.txt/index.html _ _ _ ___ _____ / \ ___| |__ ___ | | __ |_ _|_ _| / _ \ / __| '_ \ / _ \| |/ / | | | | / ___ \\__ \ | | | (_) | < | | | | /_/ \_\___/_| |_|\___/|_|\_\ |___| |_| spring.application.name=SpringBootRunnersApplicationDemo spring.banner.location=classpath:banner.txt >>> customized the location of spring boot banner spring.main.banner-mode=console NOTE ==== When we are moving the banner.txt file to required location at that time we need to update the maven project compulsory to reflect project structure. Spring Boot Runners =================== * Spring Boot Runners are nothing but java classes come spring beans in spring boot application. * Spring Boot Runners are used to execute the piece of code automatically after the spring boot application startup. * Spring Boot Runners are two types i.e., 1) CommandLineRunner 2) ApplicationRunner * The above Runners are Callback interfaces i.e.,Interface methods will be executed automatically by IOC Container. * CommandLineRunner(I),ApplicationRunner(I) are an Functional Interfaces(An Interface which contains exactly single abstract method) * Functional Interfaces abstract methods can be refer through "Lambda Expresssion"(Nameless Method (NoReturnType,NoModifier,NomethodName)). Example : public void display(){ System.out.println("Welcome"); } ()->{ System.out.println("Welcome"); } * CommandLinerRunner(I),ApplicationRunner(I) contains same method name i.e., run() * CommandLineRunner(I) >>>> public void run(String... args); >> This Runners is used Just like Command Line Arguments. CommandLineArguments >>>> The arguments which we are passing to main method while executing the Java Program. Example::::: javac EmployeeClient.java >>> Compilation Statement java EmployeeClient 123 Mahesh Male Hyderabad 123232 * ApplicationRunner(I) >>>>> public void run(ApplicationArguments arguments) >> This runner is useful to supply two types values 1) non option values Ex: ganesh suresh mahesh naresh nagesh 2) option values Ex: --username=system --password=mananger --database=oracle' 1) Always Runners are recommended to define the exeuction logic of an Spring Boot Application 2) Generally Application contains some static data and this data will be common for entire application that static data retrevial logic should be part of runners. 3) Keeping ready for Database tables with some Data(Master Data). 4) Monitoring Activities(Database,MailServer,MessagingQueue etc.,) 5) Sending email notifications to admin people. Example ======= EmailRunner.java ================ package com.ashokit.runners; import java.util.Arrays; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class EmailRunner implements CommandLineRunner{ public EmailRunner() { System.out.println("EmailRunner Class Constructors...."); } @Override public void run(String... args) throws Exception { System.out.println("EmailRunner CommandLine Args:::" + Arrays.toString(args)); } } TestRunner.java =============== package com.ashokit.runners; import java.util.Arrays; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class TestRunners implements CommandLineRunner { public TestRunners() { System.out.println("TestRunners Class Constructors...."); } @Override public void run(String... args) throws Exception { System.out.println("TestRunner CommandLine Args:::" + Arrays.toString(args)); } } Running the Application ======================== 1) Right click on Main class choose the option "Run As" >>>> Select Option as "Run Configurations" >>>> Will open the "Run Configurations" Dialog and select "Arguments" Tab and provide some values under "Program Arguments"(CommandLine Arguments) "AshokIT Hyderabad Ameerpet 123 mahesh.ashokit@gmail.com" 2) After providing the above values click on "Apply" button and again Click on "Run" button on it. OUTPUT ====== _ _ _ ___ _____ / \ ___| |__ ___ | | __ |_ _|_ _| / _ \ / __| '_ \ / _ \| |/ / | | | | / ___ \\__ \ | | | (_) | < | | | | /_/ \_\___/_| |_|\___/|_|\_\ |___| |_| :::: Spring Boot Version ::::: - 3.1.0 EmployeeController Class Constructor..... EmployeeDao Class Constructor..... EmailRunner Class Constructors.... TestRunners Class Constructors.... EmployeeService Class Constructor..... WelcomeBean Class Constructor..... EmailRunner CommandLine Args:::[--spring.output.ansi.enabled=always, AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com] TestRunner CommandLine Args:::[--spring.output.ansi.enabled=always, AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com] NOTE ==== * If we observe the above output of Spring Boot Application First it got created object for EmailRunner and then followed with TestRunner classes because Spring container will follows the Runner class object creation in alphabetical order and its applicable for Springboot 3.1.x * If we want to create an object by IOC Container in order fashion we need to use the annotation i.e.,@Order(1).... ApplicationRunner ================= * ApplicationRunner(I) >>>>> public void run(ApplicationArguments arguments) >> This runner is useful to supply two types values 1) non option values Ex: ganesh suresh mahesh naresh nagesh 2) option values Ex: --username=system --password=mananger --database=oracle' 1) Always Runners are recommended to define the execution logic of an Spring Boot Application 2) Generally Application contains some static data and this data will be common for entire application that static data retrevial logic should be part of runners. 3) Keeping ready for Database tables with some Data(Master Data). 4) Monitoring Activities(Database,MailServer,MessagingQueue etc.,) 5) Sending email notifications to admin people. Example Application =================== MessageQueueRunner.java ======================= package com.ashokit.runners; import java.util.Iterator; import java.util.Set; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class MessageQueueRunner implements ApplicationRunner{ public MessageQueueRunner() { System.out.println("MessageQueueRunner constructor"); } @Override public void run(ApplicationArguments args) throws Exception { System.out.println("MessageQueueRunner run method class...."); System.out.println("Non-option Arguments(CLA):::::" + args.getNonOptionArgs()); System.out.println("Option Arguments:::::" + args.getOptionNames()); System.out.println("DatabaseUsername::::::::" + args.getOptionValues("DatabaseUsername")); System.out.println("DatabasePassword::::::::" + args.getOptionValues("DatabasePassword")); Set optionNames = args.getOptionNames(); //traditional process Iterator iterator = optionNames.iterator(); while(iterator.hasNext()) { //current key String propertyKey = iterator.next(); //key Associated value String propertyValue = args.getOptionValues(propertyKey).get(0); System.out.println(propertyKey + " -----" + propertyValue); } //Java8 Stream how to process the set object optionNames.stream() //converting the collection objection into java8 stream object Stream .forEach(eachkey ->{ String eachValue = args.getOptionValues(eachkey).get(0); System.out.println(eachkey + "========" + eachValue); }); } } OUTPUT ====== _ _ _ ___ _____ / \ ___| |__ ___ | | __ |_ _|_ _| / _ \ / __| '_ \ / _ \| |/ / | | | | / ___ \\__ \ | | | (_) | < | | | | /_/ \_\___/_| |_|\___/|_|\_\ |___| |_| :::: Spring Boot Version ::::: - 3.1.0 2023-06-20T06:50:21.172+05:30  INFO 15296 --- [ main] com.ashokit.Application  : Starting Application using Java 17.0.7 with PID 15296 (F:\ASHOKIT_WORKSPACE\31_SPRINGBOOT_AND_MICROSERVICES\APPS_WORKSPACE\09_SpringBoot_FirstApplication\target\classes started by NEW in F:\ASHOKIT_WORKSPACE\31_SPRINGBOOT_AND_MICROSERVICES\APPS_WORKSPACE\09_SpringBoot_FirstApplication) 2023-06-20T06:50:21.175+05:30  INFO 15296 --- [ main] com.ashokit.Application  : No active profile set, falling back to 1 default profile: "default" EmployeeController Class Constructor..... EmployeeDao Class Constructor..... DatabaseRunner Class Constructors.... EmailRunner Class Constructors.... MessageQueueRunner constructor TestRunners Class Constructors.... EmployeeService Class Constructor..... WelcomeBean Class Constructor..... 2023-06-20T06:50:21.669+05:30  INFO 15296 --- [ main] com.ashokit.Application  : Started Application in 0.815 seconds (process running for 1.365) MessageQueueRunner run method class.... Non-option Arguments(CLA):::::[AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com] Option Arguments:::::[spring.output.ansi.enabled, DatabaseUsername, DatabasePassword] DatabaseUsername::::::::[system] DatabasePassword::::::::[Manager] spring.output.ansi.enabled -----always DatabaseUsername -----system DatabasePassword -----Manager spring.output.ansi.enabled========always DatabaseUsername========system DatabasePassword========Manager DatabaseRunner CommandLine Args:::[--spring.output.ansi.enabled=always, AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com, --DatabaseUsername=system, --DatabasePassword=Manager] EmailRunner CommandLine Args:::[--spring.output.ansi.enabled=always, AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com, --DatabaseUsername=system, --DatabasePassword=Manager] TestRunner CommandLine Args:::[--spring.output.ansi.enabled=always, AshokIT, Hyderabad, Ameerpet, 123, mahesh.ashokit@gmail.com, --DatabaseUsername=system, --DatabasePassword=Manager] NOTE ==== * CommandLineRunner was introducted in SpringBoot 1.x Version and its suitable processing non-option values (or) CommandLine Arguements. * ApplicationRunner was introduced in SpringBoot 2.x version and its suitable processsing option values(key-value) & Non- Option values.