Sunday, February 13, 2011

Spring Helloworld Representative Inward Coffee Using Notation In Addition To Autowiring

Spring framework has gone a duad of releases since I in conclusion portion the Spring hullo basis representative alongside XML configuration. In this article, I am going to explicate to you lot how to do a Spring hullo basis representative alongside Spring 4.2 release in addition to yesteryear using Annotation for dependency injection in addition to autowiring. So no to a greater extent than XML files to specify edible bean dependencies. It's a unproblematic programme that shows how you lot tin utilisation the Spring framework to do Services that are loosely coupled. The representative volition exhibit you lot the basic concept of dependency injection yesteryear creating a unproblematic Java application that greets the user. It's genuinely a lilliputian fleck complex version of a unproblematic Helloworld programme but if you lot require decoupling in addition to in-direction you lot require to bring to a greater extent than or less marking of complexity. That's the toll you lot require to pay to accomplish the flexibility inwards your code.

In this example, I receive got a GreetingSevice interface which has but i method greet(). This method is supposed to render a greeting of the hateful solar daytime similar "Good Morning", "Good AfterNoon, "Good Evening" etc.

Then I receive got a GreetingBot which prints greeting. This shape is decoupled from the GreetingService implementation, alongside Spring Framework wiring everything together. This agency you lot tin render whatever variety of GreetingService to greet the user you lot desire similar "Hi", "Hello", "Howdy" or whatever you lot like.

This is possible because GreetingBot calls GreetingService.greet() method to impress messages. The expert affair is that you lot don't require to inject whatever dependency, everything is wired yesteryear Spring framework using auto-wiring.

If you lot are non familiar alongside auto-wiring, I advise you lot depository fiscal establishment correspond a comprehensive Spring framework course of written report like Spring MasterClass - Beginner to Expert. There are a lot of unlike options for wiring in addition to this course of written report volition exhibit you lot that inwards detail.




Java Source files in addition to classes

GreetingService.java
This is our Service interface, which defines a service method, implemented yesteryear a Service provider class.

package hello;   public interface GreetingService {   String greet(); }


GreetingBot.java
H5N1 shape that uses the GreetingService interface to impress greetings. In other words, this is the shape which greets user but it is subject on GreetingService for that in addition to Spring framework provides that dependency to this class. At runtime, Spring Framework injects an instance of GreetingService to this class, which is thence used yesteryear the print() method.

package hello;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;   @Component public class GreetingBot {     final private GreetingService service;     @Autowired   public GreetingBot(GreetingService service) {     this.service = service;   }     public void print() {     System.out.println(this.service.greet());   } }


Main.java
This is our application class, this is the shape from the execution of our Java application starts. This shape uses before classes to construct an application. This is the shape that is also annotated alongside @Configuration in addition to @ComponentScan annotations which agency it volition hold out used every bit configuration every bit well.

If you lot await at the code, you lot volition give away a main() method, the entry signal of Java application. In this method, the offset business of code is nearly ApplicationContext, which represents a Spring container. In this case, I receive got used AnnotationConfigApplicatoinContext, which is i implementation of this interface in addition to piece of job based upon annotations.

If you lot see, nosotros don't receive got whatever Spring XML config file, thence how does the container know nearly Spring bean? Well, that's where @Bean annotation is used. If you lot await closely, you lot volition come across nosotros receive got a method called mockGreetingService() which returns a mock implementation of GreetingService implementation, this method is annotated alongside @Bean annotations in addition to Spring uses this method to inject dependency on GreetingBot class.

When nosotros telephone weep upwards the context.getBean() method it returns an instance of GreetingBot which is properly configured alongside a mock implementation fo GreetingService interface. This all happens nether the hood in addition to its completely transparent to Java developer.  Btw, if you lot are interested to larn to a greater extent than you lot tin see Spring Framework 5: Beginner to Guru to larn to a greater extent than nearly Spring container in addition to how precisely the Spring framework works.


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

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


You tin come across that our programme worked fine in addition to it printed "Good Day!" which comes from the mock implementation of the GreetingService interface. In this program, I receive got used a duad of essential Spring annotations similar @Bean, @Configuration, @ComponentScan, in addition to @Component, which may seem alien to many of you.

H5N1 edible bean is zilch but a replacement of edible bean tag inwards XML, ComponentScan a variety of auto-wiring, a Configuration agency this shape contains edible bean definitions in addition to a shape annotated alongside @Component agency it volition hold out detected for auto-wiring.

These are but basic materials but you lot desire to larn more, depository fiscal establishment correspond out Learn Spring: The Certification Class yesteryear Eugen Paraschiv of Baeldung, i of swain blogger in addition to jump instructor. It's genuinely i of the best course of written report to larn Spring five in addition to Spring Boot two from scratch, inwards a guided, code-focused way

 Spring framework has gone a duad of releases since I in conclusion portion the  Spring HelloWorld Example inwards Java using Annotation in addition to Autowiring



Required Dependencies (JAR Files)

If you lot are non using Maven, thence you lot require to seat a lot of JAR files inwards your application's classpath or if you lot are using Eclipse thence on its construct path. Spring Framework includes a seat out of unlike modules for unlike functionality, in addition to this application volition alone utilisation the marrow functionality provided inwards spring-context, which provides marrow functionality, but but including spring-context-4.2.1.RELEASE.jar volition non hold out enough.

You volition require a few to a greater extent than JAR i yesteryear i to satisfy both compile-time in addition to runtime dependency in addition to avoid those dreaded NoClassDefFoundError in addition to ClassNotFoundExceptions.

In short, you lot volition require the next JAR to run this Spring 4.2 HelloWorld Program inwards 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


Yes, that many JARs you lot volition need, but if you lot utilisation Maven or Gradle thence you lot but require to specify the next dependency into your pom.xml file and

<dependencies>   <dependency>      <groupId>org.springframework</groupId>     <artifactId>spring-context</artifactId>     <version>4.2.4.RELEASE</version>   </dependency> </dependencies>    
in addition to for Gradle:

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




Error:

It may hold out possible that when you lot offset run the programme you lot acquire to a greater extent than or less error, mainly because your environs would hold out unlike than mine (that's where Docker helps, along alongside programme it also allows you lot to bring the environs needed yesteryear that program). I also faced i mistake spell writing this programme in addition to I receive got posted hither but inwards instance if you lot acquire the same one

Exception inwards thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:158)
at org.springframework.context.support.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 hello.Application.main(Application.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... five more

Solution:

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


That's all nearly how to write Spring 4.2 HelloWorld representative inwards Eclipse IDE without using Maven. In this example, nosotros receive got also used Annotation in addition to Autowiring to acquire rid of the XML configuration file. We receive got used AnnotationConfigApplicationContext as Bean container instead of ClassPathApplicationContext, which scans Spring config files in addition to classpaths to inject the dependency.

Further Learning
Spring Framework 5: Beginner to Guru
features)
  • Top five 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 utilisation inwards their day-to-day life (tools)
  • 10 Tips to perish a ameliorate Java developer inwards 2019 (tips)
  • 3 Best Practices Java Programmers tin larn from Spring (best practices)
  • 5 courses to larn Spring Boot in addition to Spring Cloud inwards 2019( courses)
  • 3 ways to alter Tomcat port inwards Spring Boot (tutorial)
  • 10 Spring MVC annotations Java developers should larn (annotations)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)
  • 10 Spring Core Annotations Java Developers should larn (annotations)

  • Thanks for reading this article thence far. If you lot give away these Spring Boot annotations useful thence delight portion alongside your friends in addition to colleagues. If you lot receive got whatever questions or feedback thence delight drib a note.

    P. S. - If you lot desire to larn Spring in addition to looking for a costless online course of written report thence you lot tin also depository fiscal establishment correspond out the Spring Core - Learn Spring Framework iv in addition to Spring Boot on Udemy, it's completely costless in addition to all you lot require to do is do an concern human relationship to enroll into this course.

    No comments:

    Post a Comment