Showing posts with label spring boot. Show all posts
Showing posts with label spring boot. Show all posts

Saturday, November 9, 2019

How To Java.Lang.Noclassdeffounderror: Org/Springframework/Beans/Factory/Smartinitializingsingleton Inward Leap Boot

Problem:
I was trying to run a HelloWorld plan using Spring Boot when I got this error:

Exception inwards thread "main" java.lang.IllegalStateException: Could non evaluate status on org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer due to internal cast non found. This tin move on if you lot are @ComponentScanning a springframework bundle (e.g. if you lot pose a @ComponentScan inwards the default bundle yesteryear mistake)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:52)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:174)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:136)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:324)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:117)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:689)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:958)
at boot.SpringBootDemo.main(SpringBootDemo.java:14)
Caused by: java.lang.NoClassDefFoundError: org/springframework/beans/factory/SmartInitializingSingleton
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at
org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:164)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:153)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:121)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:95)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:46)
... xvi more
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.SmartInitializingSingleton
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 33 more



I had the right starter dependency i.e. spring-boot-starter-web too I was using @SpringBootApplication musical note on my Main cast to run it within an embedded container.

I had created a Simple RESTful spider web service amongst a controller cast returning "Hello Spring Boot" equally shown below:

package boot;  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;  @SpringBootApplication public class SpringBootDemo {    public static void main(String args[]) {     SpringApplication.run(SpringBootDemo.class, args);   }  }  @RestController class HelloControler {    @RequestMapping("/")   public String hello() {     return "Hello Spring Booot";   }  }

And my pom.xml (Maven dependency file looked similar below):

<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>SpringMavenDemo</groupId>     <artifactId>SpringMavenDemo</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>MavenDemo</name>     <build>         <sourceDirectory>src</sourceDirectory>         <plugins>             <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <version>3.1</version>                 <configuration>                     <source>1.7</source>                     <target>1.7</target>                 </configuration>             </plugin>         </plugins>     </build>     <dependencies>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>             <version>1.2.7.RELEASE</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-databind</artifactId>             <version>2.2.3</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-web</artifactId>             <version>4.0.0.RELEASE</version>         </dependency>      </dependencies> </project>

There are 3 errors inwards this stack trace:

1. The Caused yesteryear java.lang.ClassNotFoundException: org.springframework.beans.factory.SmartInitializingSingleton

2. The Caused by: java.lang.NoClassDefFoundError: org/springframework/beans/factory/SmartInitializingSingleton

3. Exception inwards thread "main" java.lang.IllegalStateException: Could non evaluate status on org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer due to internal cast non found.

This tin move on if you lot are @ComponentScanning a boundary framework bundle (e.g. if you lot pose a @ComponentScan inwards the default bundle yesteryear mistake)


Solution:

The argue was next conflicting dependencies whihc I stimulate got already had inwards my project, exactly inwards the pom.xml.
<dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-databind</artifactId>     <version>2.2.3</version> </dependency> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-web</artifactId>     <version>4.0.0.RELEASE</version> </dependency>

 Main argue was incompatible version of Spring library inwards the classpath. Earlier I had used spring-web 4.0.0 unloosen but Spring Boot 1.2.7 spider web starter ask higher version of library. The cast which was inwards enquiry i.e. SmartInitializingSingleton wasn't introduce inwards before version of library.

After I take those maven dependencies, my projection but ran fine. There was no error inwards the log file too I tin run across the Spring Boot printed inwards the log file. As shown inwards next screenshot:

propertySourcesPlaceholderConfigurer due to internal cast non establish How to java.lang.NoClassDefFoundError: org/springframework/beans/factory/SmartInitializingSingleton inwards Spring Boot



That's all almost how to produce "java.lang.NoClassDefFoundError: org/springframework/beans/factory/SmartInitializingSingleton" error inwards Spring Boot. As amongst whatsoever other ClassNotFoundException or NoClassDefFoundError, this was likewise related to loading incorrect cast from the classpath. Just last careful non to mix private dependency amongst Spring kicking starter dependency unless you lot certain that the explicit dependency is complete, non introduce equally purpose of starter dependency.

Further Learning
Spring Framework 5: Beginner to Guru
Master Microservices amongst Spring Boot too Spring Cloud 
Official Spring Boot Reference Guide

Thanks for reading this article too then far. If you lot are facing the same occupation too if this article helped you lot to solve your occupation delight part amongst your friends too colleagues. 

Friday, November 8, 2019

Top Fifteen Restrain Kick Interview Questions Amongst Answers For Java/Jee Programmers

Hello guys, if yous are preparing for your adjacent Java interview together with Job description mentioned most Spring framework, together with so yous should also gear upward about Spring Boot interview questions to avoid disappointment. The Spring Boot is similar a shot the criterion way to exercise Spring framework for Java evolution together with almost all the companies are moving from the traditional way of using Spring Framework to to a greater extent than modern Spring Boot way. Gone are the days, where questions similar guide maintain yous used Spring Boot was asked to the developer. Nowadays interview expects to a greater extent than cognition of Spring Boot from candidates together with in that place are reasons for it, which we'll explore inwards this article.

Spring Boot aims to simplify Java evolution alongside Spring yesteryear removing major hurting points alongside abide by to configuration, dependency management together with ease of development.  As Craig Walls position inwards Spring kicking inwards Action, It's likely the best matter happened to Java afterward JDK 1.5 release and the introduction of Spring Framework itself about fifteen years back.

It introduces a host of features e.g. starter dependency, auto-configuration, embedded server, Spring Boot CLI, Spring Actuator, Spring Initializer etc to accept the Java evolution alongside Spring to adjacent score together with that's why Spring Boot interview questions are becoming increasingly mutual inwards Java interviews.

In guild to answer Spring Boot query alongside confidence, yous non alone know what occupation Spring Boot solves but also in-depth cognition of about of its substance features similar auto-configuration together with starter dependencies. These 2 features eliminate a lot of configuration together with setup piece of work from Spring-based Java application.

Btw, If yous are non familiar alongside them I start propose yous buy the farm through a beginners shape similar Spring Boot Essentials to acquire up-to-speed. Once yous guide maintain skilful cognition of Spring Boot, yous tin endeavor these questions.




10 Spring Boot Interview Questions for Java Developers

Here is my listing of about of the most mutual Spring Boot Interview Questions from Java interviews. These questions embrace most of Spring Boot features e.g. auto-configuration, starter dependencies, Spring Actuator, Spring Initializer, Spring Boot CLI etc.

They are also collected from Java interviews for both intermediate together with experienced Java developers e.g. from 2 to five years of experience.


1. What is Spring Boot? Why should yous exercise it?
Spring Boot is about other Java framework from Sring umbrella which aims to simplify the exercise of Spring Framework for Java development. It removes most of the hurting associated alongside dealing alongside Spring e.g. a lot of configuration together with dependencies together with a lot of manual setups.

Why should yous exercise it? Well, Spring Boot non alone provides a lot of convenience yesteryear auto-configuration a lot of things for yous but also improves the productivity because it lets yous focus alone on writing your describe of piece of work organisation logic.

For example, you don't demand to setup a Tomcat server to run your spider web application. You tin only write code together with run it every bit Java application because it comes alongside an embedded Tomcat server. You tin also create a JAR file or WAR file for deployment based on your convenience.

In short, in that place are many reasons to exercise Spring Boot. In fact, it's similar a shot the criterion way to prepare Java application alongside Spring framework.



2. What are about of import features of using Spring Boot?
This is a skilful subjective query together with used yesteryear the interviewer to guess the sense of a candidate alongside Spring Boot. Anyway, next are about of the of import features of Spring Boot framework:

1. Starter dependency
This characteristic aggregates mutual dependencies together. For example, if yous desire to prepare Spring MVC based RESTful services together with so instead of including Spring MVC JAR together with Jackson JAR file into classpath yous tin only specify spring-boot-web-starter together with it volition automatically download both those JAR files. Spring Boot comes alongside many such starter dependencies to ameliorate productivity.

2. Auto-Configuration
This is about other awesome features of Spring Boot which tin configure many things for you. For example, If yous are developing Spring spider web application together with Thymeleaf.jar is nowadays on the classpath together with so it tin automatically configure Thymeleaf template resolver, see resolver, together with other settings. H5N1 skilful cognition of auto-configuration is required to buy the farm an experienced Spring Boot developers.

3. Spring Initializer
H5N1 spider web application which tin create initial projection construction for you. This simplifies initial projection setup part.

4. Spring Actuator
This characteristic provides a lot of insights of a running Spring kicking application. For example, yous tin exercise Actuator to detect out which beans are created inwards Spring's application context together with which asking path are mapped to controllers.

5. Spring CLI
This is about other awesome characteristic of Spring Boot which actually takes Spring evolution into adjacent level. It allows yous to exercise Groovy for writing Spring kicking application which way a lot to a greater extent than concise code.

If yous are interested inwards learning to a greater extent than most these essential Spring Boot features together with so Dan Vega's Learn Spring Boot - Rapid Spring Application Development is a nifty house to start with.


 if yous are preparing for your adjacent Java interview together with Job description mentioned most Spr Top fifteen Spring Boot Interview Questions alongside Answers for Java/JEE Programmers





3. What is auto-configuration inwards Spring boot? how does it help? Why Spring Boot is called opinionated?
There are a lot of questions inwards this i query itself, but let's start tackle auto-configuration. As explained inwards the previous example, it automatically configures a lot of things based upon what is nowadays inwards the classpath.

For example, it tin configure JdbcTemplate if its nowadays together with a DataSource edible bean are available inwards the classpath. It tin fifty-fifty exercise about basic spider web safety materials if Spring safety is nowadays inwards the classpath.

Btw, if yous are non familiar alongside saltation safety library together with so banking venture check out Spring Security Masterclass to acquire to a greater extent than most it. It's i of the most of import tools to secure modern-day Java application.

Anyway, the betoken is auto-configuration does a lot of piece of work for yous alongside abide by to configuring beans, controllers, see resolvers etc, so it helps a lot inwards creating a Java application.

Now, the big questions come, why it's considered opinionated? Well because it makes a judgment on its own. Sometimes it imports things which yous don't want, but don't worry, Spring Boot also provides ways to override auto-configuration settings.

It's also disabled yesteryear default together with yous demand to exercise either @SpringBootApplication or @EnableAutoConfiguration annotations on the Main shape to enable the auto-configuration feature. See Spring Boot Essentials for learning to a greater extent than most them.




4. What is starter dependency inwards Spring Boot? how does it help?
This query is to a greater extent than oft than non asked every bit a follow-up of the previous query every bit it's quite similar to auto-configuration together with many developers acquire confused betwixt both of them. As the shout out suggests, starter dependency bargain alongside dependency management.

After examining several Spring-based projects Spring guys notice that in that place is ever about laid of libraries which are used together e.g. Spring MVC alongside Jackson for creating RESTful spider web services. Since declaring a dependency inwards Maven's pom.xml is the pain, they combined many libraries into i based upon functionality together with created this starter package.

This non alone frees yous from declaring many dependencies but also fees yous from compatibility together with version mismatch issue. Spring Boot starter automatically pulls compatible version of other libraries so that yous tin exercise them without worrying most whatever compatibility issue.



5. What is the divergence betwixt @SpringBootApplication together with @EnableAutoConfiguration annotation?
Even though both are essential Spring Boot application together with used inwards the Main shape or Bootstrap shape in that place is a subtle divergence betwixt them. The @EnableAutoConfiguration is used to enable auto-configuration but @SpringBootApplication does a lot to a greater extent than than that.

It also combines @Configuration together with @ComponentScan annotations to enable Java-based configuration together with constituent scanning inwards your project.

The @SpringBootApplication is inwards fact combination of @Configuration, @ComponentScan together with @EnableAutoConfiguration annotations. You tin also banking venture check Spring Boot MasterClass to acquire to a greater extent than most this annotation together with it's used.

Also, this Spring Boot query was latterly asked to i of my friends inwards his final interview alongside a big Investment bank. He was interviewing for a front-office Java spider web application which uses Spring Boot inwards the back-end.



6. What is Spring Initializer? why should yous exercise it?
One of the hard things to start alongside a framework is initial setup, especially if yous are starting from scratch together with yous don't guide maintain a reference setup or project. Spring Initializer addresses this occupation inwards Spring Boot.

It's zero but a spider web application which helps yous to create initial Spring kicking projection construction together with provides Maven or Gradle gear upward file to gear upward your code.

I highly recommend to exercise it if yous are starting the start time. If yous desire about assistance, yous tin banking venture check out this Spring Boot MasterClass.

 if yous are preparing for your adjacent Java interview together with Job description mentioned most Spr Top fifteen Spring Boot Interview Questions alongside Answers for Java/JEE Programmers




7. What is Spring Actuator? What are its advantages?
This is an interesting Spring Boot query together with mostly asked on Java roles which also has about back upward responsibility. Spring Actuator is about other cool Spring Boot characteristic which allows seeing within a running application.

Yes, yous read it correctly. It allows yous to run across within an application. Since Spring Boot is all most auto-configuration it makes debugging hard together with at about betoken inwards time, yous desire to know which beans are created inwards Spring's Application Context together with how Controllers are mapped. Spring Actuator provides all that information.

It provides several endpoints e.g. a REST endpoint to recollect this form of information over the web. It also provides a lot of insight together with metrics most application wellness e.g. CPU together with retentivity usage, number of threads etc.

It also comes alongside a remote rhythm out which yous tin exercise to securely buy the farm within Spring Boot application together with run about command to let out the same laid of data. You tin fifty-fifty exercise JMX to command this behaviour at runtime.

Btw, it's of import to secure your Spring Actuator endpoints because it exposes a lot of confidential information together with a potentially unsafe one-two. For example, yesteryear using /showdown endpoint yous tin kill a Spring Boot application.

But, don't worry. You tin exercise Spring Security to secure Spring Actuator endpoints. If yous are non familiar alongside Spring Security together with so yous tin banking venture check out Spring Security Certification Class to acquire most it.



8. What is Spring Boot CLI? What are its benefits?
Spring Boot CLI is a command describe interface which allows yous to create Spring-based Java application using Groovy. Since it's used Groovy, it allows yous to create Spring Boot application from the command describe without ceremony e.g. yous don't demand to define getter together with setter method, or access modifiers, render statements etc.

It's also really powerful together with tin auto-include a lot of library inwards Groovy's default packet if yous tumble out to exercise it.

For example, if yous exercise JdbcTempalte, it tin automatically charge that for you. If yous are interested inwards learning Spring Boot CLI, I recommend reading Spring Boot inwards Action book, about other masterpiece from Craig Walls afterward Spring inwards Action.

 if yous are preparing for your adjacent Java interview together with Job description mentioned most Spr Top fifteen Spring Boot Interview Questions alongside Answers for Java/JEE Programmers



9. Where exercise yous define properties inwards Spring Boot application?
You tin define both application together with Spring kicking related properties into a file called application.properties. You tin create this file manually or yous tin exercise Spring Initializer to create this file, albeit empty.

You don't demand to exercise whatever special configuration to instruct Spring Boot charge this file. If it exists inwards classpath together with so Spring Boot automatically loads it together with configure itself together with application code according.

For example, yous tin exercise to define a belongings to modify the embedded server port inwards Spring Boot, which is also our adjacent question.



10. Can yous modify the port of Embedded Tomcat server inwards Spring boot? If Yes, How?
Yes, nosotros tin modify the port of Embedded Tomcat Server inwards Spring Boot yesteryear adding a belongings called server.port inwards the application.properties file.

As explained inwards the previous question, this belongings file is automatically loaded yesteryear Spring Boot together with tin survive used to configure both Spring Boot every bit good every bit application code.

If yous demand an example, yous tin run across this measuring yesteryear measuring tutorial to modify the port of Embedded Tomcat Server inwards Spring Boot. You tin farther see Learn Spring Boot inwards 100 Steps to acquire to a greater extent than most essential Spring Boot concepts together with how to exercise them inwards a existent project.

 if yous are preparing for your adjacent Java interview together with Job description mentioned most Spr Top fifteen Spring Boot Interview Questions alongside Answers for Java/JEE Programmers



11. What is the divergence betwixt an embedded container together with a WAR?
The primary divergence betwixt an embedded container together with a WAR file is that yous tin Spring Boot application every bit a JAR from the command prompt without setting upward a spider web server. But to run a WAR file, yous demand to start laid upward a web server similar Tomcat which has Servlet container together with and so yous demand to deploy WAR there.


12. What embedded containers does Spring Boot support?
Spring Boot back upward 3 embedded containers: Tomcat, Jetty, together with Undertow. By default, it uses Tomcat every bit embedded containers but yous tin modify it to Jetty or Undertow.


13. What are about mutual Spring Boot annotations?
Some of the most mutual Spring Boot annotations are @EnableAutoConfiguration, @SpringBootApplication, @SpringBootConfiguration, together with @SpringBootTest.

The @EnableAutoConfiguration is used to enable auto-configuration on Spring Boot application, field @SpringBootApplication is used on the Main class to allow it to run a JAR file. @SpringBootTest is used to run unit of measurement attempt on Spring Boot environment.


14. Can yous shout out about mutual Spring Boot Starter POMs?
Some of the most mutual Spring Boot Start dependencies or POMs are spring-boot-starter, spring-boot-starter-web, spring-boot-starter-test. You tin exercise spring-boot-starter-web to enable Spring MVC inwards Spring Boot application.


15. Can yous command logging alongside Spring Boot? How?
Yes, nosotros tin command logging alongside Spring Boot yesteryear specifying log levels on application.properties file. Spring Boot loads this file when it exists inwards the classpath together with it tin survive used to configure both Spring Boot together with application code.

Spring Boot uses Commons Logging for all internal logging together with yous tin modify log levels yesteryear adding next lines inwards the application.properties file:

logging.level.org.springframework=DEBUG
logging.level.com.demo=INFO


That's all most about of the common Spring Boot Interview Questions for Java developers. If yous are preparing for Java evolution interview where Spring Boot is required every bit a science together with so yous should survive familiar alongside these interview questions. They non alone assist yous to exercise good inwards your interview but also encourage yous to acquire cardinal Spring Boot concepts inwards details to brand the best exercise of it.

Further Learning
Spring Framework Master Class - Beginner to Expert
Master Microservices alongside Spring Boot together with Spring Cloud
Master Hibernate together with JPA alongside Spring Boot inwards 100 Steps
Spring Boot Reference Guide
5 Free Spring Framework together with Spring Boot Courses
Spring Boot: Efficient Development, Configuration, together with Deployment

Thanks for reading this article so far. If yous similar these Spring Boot Interview Questions together with so delight portion alongside your friends together with colleagues. If yous guide maintain whatever feedback or dubiousness together with so delight drib a note.

Thursday, November 7, 2019

Difference Betwixt @Springbootapplication Vs @Enableautoconfiguration Annotations Inward Trammel Boot

Even though both @SpringBootApplication as well as @EnableAutoConfiguration tin hold out used to enable the auto-configuration characteristic of Spring Boot in that place is a subtle departure betwixt them. The @SpringBootApplication does much to a greater extent than than what @EnableAutoConfiguration do. It's genuinely a combination of 3 annotations: @Configuration which is used inward Java-based configuration on Spring framework, @ComponentScan to enable constituent scanning of components you lot write e.g. @Controller classes, as well as @EnableAutoConfgiuration itself, which is used to enable auto-configuration inward Spring Boot application. Spring Boot designers realize that these 3 annotations are oftentimes used together hence they bundled them into @SpringBootApplicaiton. Now, instead of 3 annotations you lot simply demand to specify 1 annotation on your Main class.

What is the departure betwixt @EnableAutoConfiguration as well as @SpringBootApplication is too a mutual Spring Boot interview interrogation as well as it was late asked 1 of my friends on his Java interview. Given the popularity of Spring Boot framework, it's skillful to know such questions earlier you lot become for your side past times side Java interview.

In this article, I'll explicate what does the @SpringBootApplication as well as @EnableAutoConfiguration practise as well as highlight about of import departure betwixt them hence that you lot tin respond this interrogation alongside confidence if you lot plow over to come across them inward your interview.




1. What is Auto-Configuration inward Spring Boot?

If you lot don't know, Spring Boot aims to simplify Java evolution alongside Spring framework. Currently, Spring does a lot for you lot but inward return, it too asks a lot from you lot inward damage of configuration as well as dependency management, Spring Boot aims to solve that problem.

The Spring Boto auto-configuration feature tries to automatically configure your Spring application based upon the JAR dependency you lot get got added inward the classpath.

For example, if HSQLDB is nowadays on your classpath as well as you lot get got non configured whatsoever database manually, Spring volition auto-configure an in-memory database for you.

By default, this auto-configuration characteristic is non enabled as well as you lot demand to opt-in for it past times adding the @EnableAutoConfiguration or @SpringBootApplicaiton annotations to 1 of your @Configuration classes, by as well as large the Main bird which is used to run your application.

Though, this is simply the tip of the iceberg. Spring Boot auto-configuration takes to a greater extent than than 200 such determination to configure your application, If you lot are interested inward learning to a greater extent than then Spring Framework Master Class - Beginner to Expert is a skillful course of report to larn Spring Boot inward depth.

 in that place is a subtle departure betwixt them Difference betwixt @SpringBootApplication vs @EnableAutoConfiguration annotations inward Spring Boot




2. Difference betwixt @EnableAutoConfiguration as well as @SpringBootApplication

Now that nosotros know what is @SpringBootApplication as well as @EnableAutoConfiguration annotation as well as what practise they do, it's fourth dimension to highlight about of import departure betwixt them.

Here is a duad of worth-noting departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration annotations of Spring Boot:

1. Availability
The @SpringBootApplicaiton is relatively novel than @EnableAutoConfiguration. It was introduced inward Spring Boot 1.2 release piece @EnableAutoConfiguation is nowadays shape the Spring Boot 1.0 release.


2. Purpose
The clear piece of work of @EnableAutoConfiguration is to enable automatic configuration characteristic of Spring Boot application which automatically configures things if sure as shooting classes are nowadays inward Classpath e.g. it tin configure Thymeleaf TemplateResolver as well as ViewResolver if Thymeleaf is nowadays inward the classpath.

On the other hand, @SpringBootApplication does 3 things, it allows you lot to run the Main bird every bit a JAR alongside an embedded container. It enables Java configuration as well as it too enables Component Scanning.


3. Uses
It's not mandatory to position @SpringBootApplication to create a Spring Boot application, you lot tin even hence occupation @Configuration as well as @EnableAutoConfiguration individually every bit shown inward the illustration given inward side past times side point.


4. Control
The @EnableAutoConfiguration annotation allows you lot to selectively exclude sure as shooting classes from auto-configuration using exclude attribute every bit shown below:

@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration {   //.. Java code }

If the bird is non on the classpath, you lot tin occupation the excludeName attribute of the @EnableAutoConfiguration annotation as well as specify the fully qualified bird name.

If you lot desire to larn to a greater extent than well-nigh this annotation, I advise you lot reading Craig Walls' (author of Spring inward Action) about other masterpiece Spring Boot inward Action.

 in that place is a subtle departure betwixt them Difference betwixt @SpringBootApplication vs @EnableAutoConfiguration annotations inward Spring Boot



3. Important points

Now that you lot sympathise the departure betwixt @EnableAutoConfiguration as well as @SpringBootApplication, it's fourth dimension to revise about of import points well-nigh these 2 of import annotations.

1. You should annotate the Main bird or Bootstrap bird alongside the @SpringBootApplication, this volition permit you lot to run every bit a JAR alongside embedded spider web server Tomcat. If you lot desire you lot tin alter that to Jetty or Undertow.


2. The @SpringBootApplication is a combination of 3 annotations @Configuration (used for Java-based configuration), @ComponentScan (used for constituent scanning), as well as @EnableAutoConfiguration (used to enable auto-configuration inward Spring Boot).


3. The @EnableAutoConfiguration annotations enable auto-configuration features of Spring Boot which configures modules based on the presence of sure as shooting classes on the classpath. For example, if Thymeleaf JAR is nowadays inward classpath as well as Spring MVC is enabled e.g. using spring-boot-web-starter parcel as well as hence it tin automatically configure template resolver as well as persuasion resolver for you.


4. The @EnableAutoConfiguration annotation is based on @Conditional annotation of Spring 4.0 which enables conditional configuration.


5. In instance of auto-configuration, manually declared beans tin override beans automatically created past times auto-configuration feature. This is achieved past times using @ConditionalOnMissingBean of Spring 4.0


6. If you lot are using @EnableAutoConfiguration classes as well as hence you lot tin selectively exclude sure as shooting classes from auto-configuration past times using exclude every bit shown below:

@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)


7. The @SpringBootApplication annotation too provides aliases to customize the attributes of @EnableAutoConfiguration as well as @ComponentScan annotations.


That's all well-nigh the departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration annotations of Spring Boot. As you lot learned, the @SpringBootApplication makes it tardily to enable auto-configuration as well as create a Bootstrap bird past times reducing the position out of annotations you lot usually demand i.e. instead of 3 annotations you lot simply demand one. But, if you lot demand to a greater extent than command over autoconfiguration as well as hence you lot should occupation @EnableAutoConfiguration, which allows you lot to exclude classes from auto-configuration.


Further Learning
Spring Framework Master Class - Beginner to Expert
Master Microservices alongside Spring Boot as well as Spring Cloud
Master Hibernate as well as JPA alongside Spring Boot inward 100 Steps
Spring Boot Reference Guide
REST alongside Spring MasterClass past times Eugen Parsaschiv
Spring Boot: Efficient Development, Configuration, as well as Deployment

Thanks for reading this article hence far. If you lot similar this article as well as my explains of departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration as well as hence delight portion alongside your friends as well as colleagues. If you lot get got whatsoever questions or feedback as well as hence delight drib a note.

Friday, November 1, 2019

3 Ways To Modify Embedded Tomcat Server Port Inwards Jump Kicking Application

If you lot know Spring Boot actually simplifies the spider web evolution yesteryear embedding essential libraries every bit good every bit a tomcat server to run Java spider web application. By default, this tomcat server listens on port 4588 in addition to yesteryear whatever argue if you lot desire to alter than Spring kicking provides several configuration options to accomplish that. For example, I wanted tomcat to psyche on port 8080 because port fourscore is forwarded to 8080 inwards our Linux machine in addition to nosotros wanted our clients to render our customer amongst a create clean URL without a port.

Since yesteryear default HTTP asking goes to port fourscore in addition to if you lot accept forwarded that asking to 8080 in addition to if your Spring Boot application is listening on that port hence you lot tin access it amongst port similar http://localhost:8080/myspringbootapp or without port similar http://localhost/myspringbootapp.


If you lot also ask to alter the port of embedded Tomcat inwards Spring Boot application hence you lot accept come upwards to the correct place. In this article, I'll demo you lot iii ways to brand your restrain kicking application psyche on a specified port.

Btw, if you lot are novel to Spring Boot hence I also propose you lot bring together a comprehensive class like Learn Spring Boot inwards 100 Steps on Udemy to acquire inwards a to a greater extent than structured way. Spring kicking is 1 of the frameworks you lot should acquire inwards 2019 in addition to coming years, non only to develop awesome application but also to remain ahead amongst competition.



1. Changing Spring Boot Port inwards Tomcat using VM options

This is my favorite means to alter the port of embedded tomcat inwards Spring kicking application, only foremost your JVM amongst -Dserver.port=8080 or --server.port=8080 in addition to it volition psyche on that port.

If you lot are running Spring kicking application every bit an executable jar, hence you lot tin run your application using coffee -jar in addition to render the JVM arguments -Dserver.port=8080 every bit shown inwards the next example:

$ coffee -jar -Dserver.port=8080 myspringbootapp.jar


If you lot are using Eclipse to run the Spring kicking application, hence you lot tin also croak Run -> Run Configurations in addition to hence Arguments tab. Here you lot tin set the VM arguments -Dserver.port=8080 every bit shown below:

 If you lot know Spring Boot actually simplifies the spider web evolution yesteryear embedding essential libr 3 Ways to alter Embedded Tomcat Server Port  inwards Spring Boot Application



2. Changing Spring Boot Port inwards Embedded Tomcat using Properties

Another means to alter the port of embedded tomcat inwards Spring Boot application is yesteryear specifying the server.port property inwards the resources file. For example, if you lot desire your Spring kicking application to psyche on port 8080 hence you lot tin specify server.port=8080 on the application.properties inwards /src/main/resources/ folder.

$ truthful cat application.properties
server.port = 8080

If you lot desire to role random port i.e. every fourth dimension your Spring kicking application starts it uses a novel port, you lot tin laid server.port=0, this is skillful if you lot don't attention close port but non advised inwards whatever environs other than your local dev environs because it tin crusade port clashing.

Also, when you lot role the random port you lot tin acquire the port information yesteryear using the @Value annotation every bit shown below:

@Value("${local.server.port}")

If you lot already accept a duo of properties for your Spring Boot application hence this is the preferred means to alter the port of embedded tomcat server inwards Spring boot.


3. Changing Spring Boot Tomcat Port Programmatically

If you lot are a purist who likes to create everything inwards Java yesteryear writing code hence this method is for you. It allows you lot to specify the tomcat port for a Spring kicking application inwards code:

@Configuration public class ServletConfig { @Bean public EmbeddedServletContainerCustomizer containerCustomizer() {    return (container -> {      container.setPort(8080);     });   } }

Though beware, if you lot ask to alter the port 1 time to a greater extent than hence you lot ask to compile in addition to rebuild the project. That's why it's ameliorate to set whatever setting on JVM declaration or belongings file. If you lot role those methods you lot tin alter the tomcat port of Spring kicking application without recompiling in addition to rebuilding them.


That's all close how to alter the port of embedded tomcat server inwards Spring Boot application. As I said, yesteryear default Spring kicking application server listens on port 4588 but you lot tin alter the port yesteryear using these methods to croak far psyche on to a greater extent than familiar port 8080 or whatever other port of your choice. I by in addition to large prefer the VM alternative but if you lot similar properties file, experience gratuitous to role it. The programmatic means is really rare in addition to alone for purists.

Further Learning
Learn Spring Boot
Master Java Web Services amongst Spring Boot
Master Hibernate in addition to JPA amongst Spring Boot inwards 100 Steps


Other Java in addition to Spring articles you lot may like
v Spring Boot Features Every Java Developer Should Know (features)
Top v Free Courses to acquire Spring in addition to Spring Boot inwards 2019 (courses)
v Course to Master Spring Boot online inwards 2019 (courses)
10 Things Java Developer should acquire inwards 2019 (goals)
10 Tools Java Developers role inwards their day-to-day life (tools)
10 Tips to croak a ameliorate Java developer inwards 2019 (tips)
3 Best Practices Java Programmers tin acquire from Spring (best practices)
v courses to acquire Spring Boot in addition to Spring Cloud inwards 2019( courses)
v Spring Boot Annotations Java developer should acquire (annotations)
v Spring Books Java developers should read inwards 2019 (books)

Thanks for reading this article hence far. If you lot honour this Spring Boot tutorial in addition to tips useful hence delight percentage amongst your friends in addition to colleagues. If you lot accept whatever questions or feedback hence delight driblet a note.

Thursday, October 31, 2019

Top Five Saltation Kicking Annotations Amongst Examples For Coffee Developers

Annotations bring completely changed the means y'all write Java code. It's straightaway impossible to write whatever Java code without using annotations but that's for good. They render a lot of value in addition to that's why it's of import for a Java developer to acquire familiar amongst essential annotations of the framework he or she is using. When I intend virtually Java, to a greater extent than or less of the essential annotations which come upward inwards our heed is @Override, @SuppressWarning in addition to @Deprecated. Similarly, if y'all are using Spring Boot framework, an extension of Spring framework which aims to simplify the Java evolution amongst Spring, y'all volition oftentimes cease of using a distich of annotations similar @SpringBootApplication or @EnableAutoConfiguration.

Many Java developer simply blindly uses annotations without knowing that what they are in addition to what they do. They simply copy-paste the code without giving much thought.

For example, the @SpringBootApplication annotation is required to most of the principal flat y'all write amongst Spring Boot, hence, most of the Java developer cease upward simply copy-pasting whole flat in addition to they trying to customize it for their ain need.

Well, null is bad, equally long equally y'all know what y'all are doing but simply learning a chip of key never hurt. Even pocket-size information that what does the especially annotation do in addition to when to exercise them volition acquire out a long means inwards improving your agreement of the code y'all write or read.

In club to span this gap, I am going to portion to a greater extent than or less of the essential Spring Boot annotations every Java developer should last familiar with. I'll simply render a quick overview amongst an instance for the sake to acquire out on this article brusk but y'all join Learn Spring Boot inwards 100 Steps to larn them inwards depth amongst to a greater extent than real-world examples.





Spring Boot Annotations Java Developer should know

Without wasting whatever to a greater extent than of your time, hither is my listing of to a greater extent than or less of the useful Spring Boot annotations which every Java developer using Spring Boot should last familiar with.

1.@SpringBootApplication

This is the most mutual Spring Boot annotations in addition to y'all volition honour it in all likelihood inwards every unmarried Spring Boot application. Since Spring Boot allows y'all to execute your Web application without deploying into whatever spider web server similar Tomcat.

You tin laissez passer on the axe run them simply similar y'all tin laissez passer on the axe run the principal flat inwards Java, this annotation is used to annotate the principal flat of your Spring Boot application. It also enables the auto-configuration characteristic of Spring Boot.

Here is an instance of using the @SpringBootApplication inwards Java:

package boot; 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;   @SpringBootApplication public class SpringBootDemo {  public static void main(String args[]) {   SpringApplication.run(SpringBootDemo.class, args); }  }  @RestController class HelloControler{   @RequestMapping("/") public String hello(){   return "Hello Spring Booot"; }  }

This is the simplest instance of RESTful spider web service y'all tin laissez passer on the axe write using Spring in addition to Java. You tin laissez passer on the axe run this similar whatever Java application past times right-clicking on the source file in addition to "Run equally Java application" inwards Eclipse. After that, the embedded Tomcat server volition start in addition to deploy this RESTful spider web service.

When y'all volition striking the URL http://localhost:8080/ (the default port for embedded tomcat server within Spring boot) y'all volition last greeted amongst "Hello Spring Boot".

Now, coming dorsum to the @SpringBootApplication annotation, it's genuinely a combination of iii annotations - @Configuration, @ComponentScan, in addition to @EnableAutoConfiguration.

If y'all know the @Configuration enables Java-based configuration in addition to the flat annotated amongst @Configuration tin laissez passer on the axe last used to define Spring Beans.

The @ComponentScan enables element scanning so that controller or whatever other element flat y'all create volition last automatically discovered in addition to registered amongst Spring Bean.

And, finally, the @EnableAutoConfiguration enables the auto-configuration characteristic of Spring Boot which tin laissez passer on the axe automatically configure surely Spring features based upon JAR available inwards Classpath. For example, if H2.jar is acquaint inwards the classpath, it tin laissez passer on the axe configure the H2 in-memory database within the Spring application context.

As explained past times Dan Vega on his Spring Boot MasterClass, Spring Boot makes to a greater extent than than 200+ conclusion to gratis y'all from mutual configuration task. If y'all desire to customize those decisions y'all tin laissez passer on the axe do so.

 Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


Btw, the @SpringBootApplication annotation is entirely available shape Spring Boot version 1.1, It wasn't purpose of Spring Boot's outset expose in addition to after added because they realize that almost all the applications were annotated amongst those iii annotations (@Configuration + @ComponentScan, in addition to @EnableAutoConfiguration).



2.@EnableAutoConfiguration

This is the master copy Spring Boot annotation which was added to enable the auto-configuration, the flagship Spring kicking characteristic which frees developers from mutual configuration task.

The auto-configuration characteristic automatically configures things if surely classes are acquaint inwards the Classpath e.g. if thymeleaf.jar is acquaint inwards the Classpath so it tin laissez passer on the axe automatically configure Thymeleaf TemplateResolver in addition to ViewResolver.

If y'all are non using @SpringBootApplication or running on Spring kicking version lower than 1.1 so y'all tin laissez passer on the axe exercise @EnableAutoConfiguration annotates to enable the auto-configuration characteristic of Spring Boot.


Another affair which is worth knowing virtually @EnableAutoConfiguration is that it allows y'all to selectively ignore surely classes from auto-configuration using exclude attribute equally shown below:

@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class SpringBootDemo {   //.. Java code }

If the flat is non on the classpath, y'all tin laissez passer on the axe exercise the excludeName attribute of the @EnableAutoConfiguration annotation in addition to specify the fully qualified flat name, equally explained past times Ranga Karnan on  Learn Spring Boot inwards 100 Steps course. One of the best course of report for beginners to larn Spring boot.

 Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


Btw, this Spring Boot annotation is genuinely useful for experienced Spring Boot programmers who intend that Spring kicking is also opinionated in addition to desire to bring to a greater extent than or less command over the auto-configuration feature.



3.@ContextConfiguration

This annotation specifies how to charge the application context land writing a unit of measurement essay for the Spring environment. Here is an instance of using @ContextConfiguration along amongst @RunWith annotation of JUnit to essay a Service flat inwards Spring Boot.

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=PaymentConfiguration.class) public class PaymentServiceTests{  @Autowired private PaymentService paymentService;  @Test public void testPaymentService(){    // code to essay PaymentService class  }  }

In this example, @ContextConfiguration flat instructs to charge the Spring application context defined inwards the PaymentConfiguration class.

Btw, fifty-fifty though it does a swell chore of loading Spring application context, it doesn't render total Spring kicking treatment.

As explained past times Craig Walls inwards Spring Boot inwards Action, the Spring Boot applications are ultimately loaded past times SpringBootApplicaiton either explicitly or using the SpringBootServletInitializer.


 Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


This non entirely leads beans inwards Spring application context but also enables logging in addition to loading of properties from external holding file like applicaiton.properties equally good equally other Spring Boot features. But, don't worry, at that spot is to a greater extent than or less other annotation which provides all of this in addition to y'all tin laissez passer on the axe exercise that to write a unit of measurement essay amongst Spring kicking treatment.



4.@SpringApplicationConfiguration

This is the annotation which addresses shortcomings of @ContextConfiguration annotation discussed inwards the previous section. It provides total Spring Boot handling to your essay classes e.g. it non entirely charge the beans inwards Spring application context but also enable logging in addition to loads properties from application.properties file.

Btw, y'all should e'er exercise @SpringApplicaitonConfiguration instead of @ContextConfigruation for writing unit of measurement essay inwards Spring boot.

Here is an instance of using @SpringApplicatoinConfiguration annotation inwards Spring boot:


@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=PaymentConfiguration.class) public class PaymentServiceTests{   ...  }

This is the same instance nosotros bring seen inwards the in conclusion department but re-written using the @SpringApplicationConfiguration annotation this time. Again, I advise y'all cheque out the Spring Boot inwards Action mass to larn to a greater extent than virtually it, 1 of the best books to larn Spring Boot framework.





5.@ConditionalOnBean

Spring Boot defines several conditional annotations for auto-configuration like @ConditionalOnBean which tin laissez passer on the axe last used to apply a configuration if the specified edible bean has been configured.


5.1 @ConditionalOnMissingBean
Similarly, y'all bring @ConditionalOnMissingBean, which enables the configuration if the specified edible bean has non already been configured.

@ConditionalOnClass
The configuration is applied if the specified flat is available on the Classpath.


5.2 @ConditioanlOnMissingClass
This is the counterpart of the previous annotation. This configuration is applied if the specified flat is non acquaint on the Classpath.


5.3 @ConditionalOnExpression
The Configuration is applied if the given Spring Expression Language (SpEL) appear evaluates to true.


5.4 @ConditionalOnJava
The Configuration is applied if the version of Java matches a specific value or make of versions.

Apart from these conditional annotations listed here, at that spot are to a greater extent than e.g. @ConditioalOnJndi, @ConditioanlOnProperty, @ConditioanlOnResource, @ConditionalOnWebApplication, in addition to @ConditionalOnNotWebApplication which plant depending upon the presence in addition to absence of to a greater extent than or less conditions.

If y'all are interested to larn to a greater extent than virtually them, I advise to acquire out through Spring Framework 5: Beginner to Guru, 1 of the best course of report to larn Conditionals in addition to Spring Boot annotations.



That's all virtually to a greater extent than or less of the essential Spring Boot annotations every Java developer should know. If y'all are using Spring Boot for creating Spring-based Java spider web application so y'all volition come upward across these annotations every straightaway in addition to then. Just knowing what they do in addition to where y'all tin laissez passer on the axe exercise volition laissez passer on y'all confidence land reading in addition to writing Spring kicking code.

Further Learning
Learn Spring Boot
Master Java Web Services amongst Spring Boot
Master Hibernate in addition to JPA amongst Spring Boot inwards 100 Steps


Other Java in addition to Spring articles y'all may like
  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • Top v Free Courses to larn Spring in addition to Spring Boot inwards 2019 (courses)
  • 5 Course to Master Spring Boot online inwards 2019 (courses)
  • 10 Things Java Developer should larn inwards 2019 (goals)
  • 10 Tools Java Developers exercise inwards their day-to-day life (tools)
  • 10 Tips to acquire a improve Java developer inwards 2019 (tips)
  • 3 Best Practices Java Programmers tin laissez passer on the axe larn from Spring (best practices)
  • 5 courses to larn Spring Boot in addition to Spring Cloud inwards 2019( courses)
  • 3 ways to modify Tomcat port inwards Spring Boot (tutorial)
  • 10 Spring MVC annotations Java developers should larn (annotations)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)


Thanks for reading this article so far. If y'all honour these Spring Boot annotations useful so delight portion amongst your friends in addition to colleagues. If y'all bring whatever questions or feedback so delight drib a note.