Friday, February 3, 2023
HomeJavaSpring HelloWorld Instance in Java Annotations and Autowiring

Spring HelloWorld Instance in Java Annotations and Autowiring [Tutorial]


It is really a bit bit complicated model of a easy Helloworld program however in the event you want decoupling and in-direction it is advisable to settle for some degree of complexity. That is the value it is advisable to pay to attain flexibility in your code.

On this instance, I’ve a GreetingSevice interface that has only one methodology greet(). This methodology is meant to return a greeting of the day like “Good Morning”, “Good AfterNoon, “Good Night” and so forth.

Then I’ve a GreetingBot which prints greeting. This class is decoupled from the GreetingService implementation, with Spring Framework wiring every little thing collectively. This implies you may present any sort of GreetingService to greet the person you need like “Hello”, “Hey”, “Howdy”, or no matter you want.

That is attainable as a result of GreetingBot calls GreetingService.greet() methodology to print messages. The nice factor is that you simply need not inject any dependency, every little thing is wired by the Spring framework utilizing auto-wiring.

If you’re not accustomed to auto-wiring, I recommend you test a complete Spring framework course like Spring MasterClass – Newbie to Knowledgeable. There are loads of totally different choices for wiring and this course will present you that intimately.

Java Supply recordsdata and courses

GreetingService.java

That is our Service interface, which defines a service methodology, carried out by a Service supplier class.

package deal hey;
 
public interface GreetingService {
  String greet();
}

GreetingBot.java

A category that makes use of the GreetingService interface to print greetings. In different phrases, that is the category that greets customers however it’s depending on GreetingService for that, and the Spring framework offers that dependency to this class. At runtime, Spring Framework injects an occasion of GreetingService to this class, which is then utilized by the print() methodology.

package deal hey;
import org.springframework.beans.manufacturing unit.annotation.Autowired;
import org.springframework.stereotype.Element;
 
@Element
public class GreetingBot {
 
  closing non-public GreetingService service;
 
  @Autowired
  public GreetingBot(GreetingService service) {
    this.service = service;
  }
 
  public void print() {
    System.out.println(this.service.greet());
  }
}

Predominant.java

That is our utility class, that is the category from which the execution of our Java utility begins. This class makes use of earlier courses to construct an utility. That is the category that can also be annotated with @Configuration and @ComponentScan annotations which implies it will likely be used as configuration as effectively.

Should you have a look at the code, you will discover a principal() methodology, the entry level of the Java utility. On this methodology, the primary line of code is about ApplicationContext, which represents a Spring container. On this case, I’ve used AnnotationConfigApplicatoinContext, which is one implementation of this interface and works based mostly upon annotations.

Should you see, we haven’t any Spring XML config file, so how does the container learn about Spring bean? Properly, that is the place @Bean annotation is used. Should you look intently, you will notice we’ve a technique known as mockGreetingService() which returns a mock implementation of GreetingService implementation, this methodology is annotated with @Bean annotations and Spring makes use of this methodology to inject dependency on GreetingBot class.

Once we name the context.getBean() methodology returns an occasion of GreetingBot which is correctly configured with a mock implementation for the GreetingService interface. This all occurs underneath the hood and it is fully clear to Java builders.  Btw, if you’re to be taught extra you may see Spring Framework 5: Newbie to Guru to be taught extra about Spring container and the way precisely the Spring framework works.

package deal hey;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
 
@Configuration
@ComponentScan
public class Predominant {
 
  @Bean
  GreetingService mockGreetingService() {
    return new GreetingService() {
      public String greet() {
        return "Good Day!";
      }
    };
  }
 
  public static void principal(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(
        Predominant.class);
    GreetingBot greeter = context.getBean(GreetingBot.class);
    greeter.print();
  }
}

Output:
Jan 14, 2016 6:30:15 PM org.springframework.context.help.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@a4a63d8: startup date [Thu Jan 14 18:30:15 SGT 2016]; root of context hierarchy
Good Day!

You’ll be able to see that our program labored advantageous and it printed “Good Day!” which comes from the mock implementation of the GreetingService interface. On this program, I’ve used a few important Spring annotations like @Bean, @Configuration, @ComponentScan, and @Element, which can appear alien to a lot of you.

A bean is nothing however a alternative of bean tag in XML, ComponentScan is a sort of auto-wiring, a Configuration means this class accommodates bean definitions, and a category annotated with @Element means it will likely be detected for auto-wiring.

These are simply primary stuff however you need to be taught extra, take a look at Be taught Spring: The Certification Class by Eugen Paraschiv of Baeldung, considered one of my fellow blogger and spring instructors. It is really top-of-the-line programs to be taught Spring 5 and Spring Boot 2 from scratch, in a guided, code-focused method

Spring HelloWorld Example in Eclipse using Annotation and Autowiring

Required Dependencies (JAR Recordsdata)

If you’re not utilizing Maven, then it is advisable to put loads of JAR recordsdata in your utility’s classpath, or if you’re utilizing Eclipse then it is construct path. Spring Framework contains plenty of totally different modules for various performance, and this utility will solely use the core performance supplied in spring-context, which offers core performance, however simply together with the spring-context-4.2.1.RELEASE.jar is not going to be sufficient.

You’ll require just a few extra JAR one after the other to fulfill each compile-time and runtime dependency and keep away from these dreaded NoClassDefFoundError and ClassNotFoundExceptions.

Briefly, you have to the next JAR to run this Spring 4.2 HelloWorld Program in Eclipse.

  • spring-context-4.2.1.RELEASE.jar
  • spring-beans-4.2.1.RELEASE.jar
  • spring-core-4.2.1.RELEASE.jar
  • commons-logging-1.0.4.jar
  • spring-aop-4.2.1.RELEASE.jar
  • spring-expression-4.2.1.RELEASE.jar

Sure, that many JARs you have to, however in the event you use Maven or Gradle then you definately simply have to specify the next dependency into your pom.xml file and

<dependencies>
  <dependency>
     <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <model>4.2.4.RELEASE</model>
  </dependency>
</dependencies>
 
 

and for Gradle:

dependencies {
   compile ‘org.springframework:spring-context:4.2.4.RELEASE’
}

Error:

It might be attainable that if you first run this system you get some error, primarily as a result of your atmosphere could be totally different than mine (that is the place Docker helps, together with this system it additionally lets you take the atmosphere wanted by that program). I additionally confronted one error whereas penning this program and I’ve posted it right here simply in case in the event you get the identical one

Exception in thread "principal" java.lang.NoClassDefFoundError: 
org/apache/commons/logging/LogFactory
at org.springframework.context.help.AbstractApplicationContext
.<init>(AbstractApplicationContext.java:158)
at org.springframework.context.help.GenericApplicationContext
.<init>(GenericApplicationContext.java:102)
at org.springframework.context.annotation.AnnotationConfigApplicationContext
.<init>(AnnotationConfigApplicationContext.java:60)
at org.springframework.context.annotation.AnnotationConfigApplicationContext
.<init>(AnnotationConfigApplicationContext.java:82)
at hey.Utility.principal(Utility.java:21)
Precipitated by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.web.URLClassLoader$1.run(Unknown Supply)
at java.safety.AccessController.doPrivileged(Native Methodology)
at java.web.URLClassLoader.findClass(Unknown Supply)
at java.lang.ClassLoader.loadClass(Unknown Supply)
at solar.misc.Launcher$AppClassLoader.loadClass(Unknown Supply)
at java.lang.ClassLoader.loadClass(Unknown Supply)
... 5 extra

Resolution:

Add Apache commons-logging framework JAR into your Eclipse construct path.

That is all about the way to write Spring 4.2 HelloWorld instance in Eclipse IDE with out utilizing Maven. On this instance, we’ve additionally used Annotation and Autowiring to eliminate the XML configuration file. We have now used AnnotationConfigApplicationContext as a Bean container as a substitute of ClassPathApplicationContext, which scans Spring config recordsdata and classpaths to inject the dependency.

Different Java and Spring articles it’s possible you’ll like

  • 5 Spring Boot Options Each Java Developer Ought to Know (options)
  • Prime 5 Free Programs to be taught Spring and Spring Boot (programs)
  • 5 Course to Grasp Spring Boot on-line (programs)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)
  • 10 Issues Java Developer ought to be taught(objectives)
  • 10 Superior Spring Boot Programs for Java Builders (programs)
  • 10 Instruments Java Builders use of their day-to-day life (instruments)
  • 10 Tricks to develop into a greater Java developer (suggestions)
  • 10 Programs to be taught Spring Safety with OAuth2 (programs)
  • 3 Finest Practices Java Programmers can be taught from Spring (finest practices)
  • 5 programs to be taught Spring Boot and Spring Cloud( programs)
  • 3 methods to vary Tomcat port in Spring Boot (tutorial)
  • 10 Spring MVC annotations Java builders ought to be taught (annotations)
  • 7 Programs to be taught Microservices in Java (programs)
  • 10 Spring Core Annotations Java Builders ought to be taught (annotations)

Thanks for studying this text to date. Should you discover these Spring Boot annotations helpful then please share them with your folks and colleagues.
If in case you have any questions or suggestions then please drop a be aware.

P. S. – If you wish to be taught Spring and in search of a free on-line course then you can too take a look at these free Spring Framework programs from websites like Udemy and Coursera. it is fully free and all it is advisable to do is create an account to enroll on this course.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments