Thursday, May 2, 2024
HomeJava5 Important Spring Boot Annotations with Examples in Java - Tutorial

5 Important Spring Boot Annotations with Examples in Java – Tutorial


Howdy guys, if you’re coding in Java for lengthy then you realize that Annotations have utterly modified the best way you write Java code. It is now unattainable to jot down any Java code with out utilizing annotations however that is for good. They supply numerous worth and that is why it is vital for a Java developer to get acquainted with important annotations of the framework she or he is utilizing. Once I take into consideration Java, a number of the important annotations which come to our thoughts are @Override, @SuppressWarning, and @Deprecated. Equally, if you’re utilizing the Spring Boot framework, an extension of the Spring framework which goals to simplify the Java improvement with Spring, you’ll typically find yourself utilizing a few annotations like @SpringBootApplication or @EnableAutoConfiguration.

Many Java developer simply blindly makes use of annotations with out realizing that what they’re and what they do. They simply copy-paste the code with out giving a lot thought.

For instance, the @SpringBootApplication annotation is required for many of the principal class you write with Spring Boot, therefore, many of the Java builders find yourself simply copy-pasting the entire class and making an attempt to customise it for their very own want.

Properly, nothing is dangerous, so long as you realize what you’re doing however simply studying a little bit of fundamentals by no means harm. Even small data that what does the actual annotation does and when to make use of them will go a great distance in enhancing your understanding of the code you write or learn.

So as to bridge this hole, I’m going to share a number of the important Spring Boot annotations each Java developer ought to be acquainted with. I will simply present a fast overview with an instance for the sake to maintain this text brief however you be a part of Study Spring Boot in 100 Steps course to study them in depth with extra real-world examples.

5 Spring Boot Annotations Each Java Developer ought to know

With out losing any extra of your time, right here is my listing of a number of the helpful Spring Boot annotations which each and every Java developer utilizing Spring Boot ought to be acquainted with.

1.@SpringBootApplication

That is the commonest Spring Boot annotation and you’ll discover it in all probability in each single Spring Boot utility. Since Spring Boot permits you to execute your Net utility with out deploying it into any internet server like Tomcat.

You’ll be able to run them identical to you possibly can run the principle class in Java, this annotation is used to annotate the principle class of your Spring Boot utility. It additionally permits the auto-configuration characteristic of Spring Boot.

Right here is an instance of utilizing the @SpringBootApplication in Java:

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


@SpringBootApplication
public class SpringBootDemo {

public static void principal(String args[]) {
  SpringApplication.run(SpringBootDemo.class, args);
}

}

@RestController
class HelloControler{ 

@RequestMapping("/")
public String good day(){
  return "Howdy Spring Booot";
}

}

That is the best instance of a RESTful internet service you possibly can write utilizing Spring and Java. You’ll be able to run this like all Java utility by right-clicking on the supply file and “Run as Java utility” in Eclipse. After that, the embedded Tomcat server will begin and deploy this RESTful internet service.

When you’ll hit the URL http://localhost:8080/ (the default port for embedded tomcat server inside Spring boot) you may be greeted with “Howdy Spring Boot”.

Now, coming again to the @SpringBootApplication annotation, it is really a mix of three annotations – @Configuration, @ComponentScan, and @EnableAutoConfiguration.

If you realize the @Configuration permits Java-based configuration and the category annotated with @Configuration can be utilized to outline Spring Beans.

The @ComponentScan permits part scanning in order that controller or another part class you create can be robotically found and registered with Spring Bean.

And, lastly, the @EnableAutoConfiguration permits the auto-configuration characteristic of Spring Boot which may robotically configure sure Spring options primarily based upon JAR out there in Classpath. For instance, if H2.jar is current within the classpath, it might configure the H2 in-memory database contained in the Spring utility context.

As defined by Dan Vega in his Spring Boot MasterClass, Spring Boot makes greater than 200+ selections to free you from widespread configuration duties. If you wish to customise these selections you are able to do so.

Top 5 Spring Boot Annotations with Examples for Java Developers

Btw, the @SpringBootApplication annotation is just out there from Spring Boot model 1.1, It wasn’t a part of Spring Boot’s first launch and was later added as a result of they notice that the majority the purposes had been annotated with these three annotations (@Configuration + @ComponentScan, and @EnableAutoConfiguration).


2.@EnableAutoConfiguration

That is the unique Spring Boot annotation which was added to allow the auto-configuration, the flagship Spring boot characteristic which frees builders from widespread configuration duties.

The auto-configuration characteristic robotically configures issues if sure lessons are current within the Classpath like if thymeleaf.jar is current within the Classpath then it might robotically configure Thymeleaf TemplateResolver and ViewResolver.

In case you are not utilizing @SpringBootApplication or operating on Spring boot model decrease than 1.1 then you need to use @EnableAutoConfiguration annotates to allow the auto-configuration characteristic of Spring Boot.

One other factor that’s price realizing about @EnableAutoConfiguration is that it permits you to selectively ignore sure lessons from auto-configuration utilizing the exclude attribute as proven under:

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

If the category isn’t on the classpath, you need to use the excludeName attribute of the @EnableAutoConfiguration annotation and specify the totally certified class identify, as defined by Ranga Karnan on  Study Spring Boot in 100 Steps course. Probably the greatest programs for rookies to study Spring boot.

@EnableAutoConfiguration Spring Boot annotation example

Btw, this Spring Boot annotation is basically helpful for skilled Spring Boot programmers who assume that Spring boot is simply too opinionated and wish to have some management over the auto-configuration characteristic.

3.@ContextConfiguration

This annotation specifies methods to load the applying context whereas writing a unit take a look at for the Spring surroundings. Right here is an instance of utilizing @ContextConfiguration together with @RunWith annotation of JUnit to check a Service class in Spring Boot.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(lessons=PaymentConfiguration.class)
public class PaymentServiceTests{

@Autowired
personal PaymentService paymentService;

@Check
public void testPaymentService(){

  // code to check PaymentService class

}

}

On this instance, @ContextConfiguration class instructs to load the Spring utility context outlined within the PaymentConfiguration class.  

Btw, despite the fact that it does a fantastic job of loading the Spring utility context, it does not present full Spring boot therapy.

As defined by Craig Partitions in Spring Boot in Motion, the Spring Boot purposes are finally loaded by SpringBootApplicaiton both explicitly or utilizing the SpringBootServletInitializer.

@ContextConfiguration Spring Boot annotation example




This not solely leads beans within the Spring utility context but additionally permits logging and loading of properties from exterior property recordsdata like applicaiton.properties in addition to different Spring Boot options. However, don’t be concerned, there’s one other annotation that gives all of this and you need to use that to jot down a unit take a look at with Spring boot therapy.

4.@SpringApplicationConfiguration

That is the annotation that addresses the shortcomings of @ContextConfiguration annotation mentioned within the earlier part. It offers full Spring Boot therapy to your take a look at lessons prefer it not solely load the beans within the Spring utility context but additionally permits logging and hundreds properties from utility.properties file.

Btw, you must all the time use @SpringApplicaitonConfiguration as an alternative of @ContextConfigruation for writing unit assessments in Spring boot.

Right here is an instance of utilizing @SpringApplicatoinConfiguration annotation in Spring boot:

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

}

This is similar instance we now have seen within the final part however re-written utilizing the @SpringApplicationConfiguration annotation this time. Once more, I recommend you try the Spring Boot in Motion guide to study extra about it, one of many greatest books to study the Spring Boot framework.

5.@ConditionalOnBean

Spring Boot defines a number of conditional annotations for auto-configuration like @ConditionalOnBean which can be utilized to use a configuration if the desired bean has been configured.

5.1 @ConditionalOnMissingBean
Equally, you’ve gotten @ConditionalOnMissingBean, which permits the configuration if the desired bean has not already been configured.

@ConditionalOnClass
The configuration is utilized if the desired class is accessible on the Classpath.

5.2 @ConditioanlOnMissingClass
That is the counterpart of the earlier annotation. This configuration is utilized if the desired class isn’t current on the Classpath.

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

5.4 @ConditionalOnJava
The Configuration is utilized if the model of Java matches a particular worth or vary of variations.

Aside from these conditional annotations listed right here, there are extra e.g. @ConditioalOnJndi, @ConditioanlOnProperty, @ConditioanlOnResource, @ConditionalOnWebApplication, and @ConditionalOnNotWebApplication which works relying upon the presence and absence of some situations.

In case you are to study extra about them, I recommend going via Spring Framework 5: Newbie to Guru, top-of-the-line programs to study Conditionals and Spring Boot annotations.

common Spring Boot annotations for Java programmers

That is all about a number of the important Spring Boot annotations each Java developer ought to know. In case you are utilizing Spring Boot for making a Spring-based Java internet utility then you’ll come throughout these annotations every so often. Simply realizing what they do and the place you need to use offers you confidence whereas studying and writing Spring boot code.

Different Java and Spring articles chances are you’ll like

  • 5 Spring Boot Options Each Java Developer Ought to Know (options)
  • Prime 5 Free Programs to study Spring and Spring Boot (programs)
  • 5 Course to Grasp Spring Boot on-line (programs)
  • 10 Programs to study Spring Safety with OAuth 2 (programs)
  • 10 Issues Java Developer ought to study (targets)
  • Prime 5 Books and Programs to study RESTful Net Service (books)
  • 10 Instruments Java Builders use of their day-to-day life (instruments)
  • 10 Tricks to turn out to be a greater Java developer (ideas)
  • Prime 5 Programs to study Microservices in Java? (programs)
  • 3 Greatest Practices Java Programmers can study from Spring (greatest practices)
  • 5 programs to study Spring Boot and Spring Cloud ( programs)
  • 3 methods to alter Tomcat port in Spring Boot (tutorial)
  • 10 Superior Spring Boot Programs for Java Programmers (programs)
  • 10 Spring MVC annotations Java builders ought to study (annotations)
  • 10 Greatest Spring Programs for Senior Java builders (greatest courses)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)

Thanks for studying this text thus far. When you discover these important Spring Boot annotations helpful then please share them with your pals and colleagues. When you’ve got any questions or suggestions then please drop a observe.


P. S. – If you wish to study Spring Boot in-depth however searching for some free sources to start out with then I additionally suggest you try this listing of 10 Free Spring Boot tutorials and programs on Medium. This listing comprises a number of the greatest free programs to study Spring Boot from Udemy, Pluralsight, Coursera, and different on-line platforms.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments