All IT Courses 50% Off
JAVA Tutorials

Spring Annotations Configuration

It is a Java-based configuration option that enables you to write the most of your Spring configuration without using XML but with the help of few Java-based annotations. The Spring annotation wiring is not turned on in Spring Framework. Therefore, you need to enable it before you can use the Spring annotation-based wiring in the Spring Configuration file. 

Below is the configuration file in case you want to use Annotation in your application:

  • @Configuration and @Bean Annotations

By using annotations, Annotating a class using @Configuration, which will indicate that the class is managed by the Spring IoC container as a source of bean definitions. 

The other one @Bean Annotation which inform Spring that a method which annotated herewith @Bean

All IT Courses 50% Off
@Configuration

public class HelloWorldDemo {

   @Bean 

   public Hello hello(){

      return new Hello();

   }

}

Here, @Bean it works as bean ID

<beans>
   <bean id = "hello" class = "com.demo.Hello" />
</beans> 

public static void main(String[] arg) {
   ApplicationContext cnt = new AnnotationConfigApplicationContext(HelloWorldDemo.class);
      Hello hello= cnt.getBean(Hello.class);
   hello.setMessage("Hello !");
   hello.getMessage();
}

Here, we can load various configuration classes as follows

public static void main(String[] args) {
   AnnotationConfigApplicationContext cnt = new AnnotationConfigApplicationContext();
   cnt.register(AppConfig.class, OtherConfig.class);
   cnt.register(AdditionalConfig.class);
   cnt.refresh();

   MyService myService = cnt.getBean(MyService.class);
   myService.doStuff();
}

@Configuration
public class HelloWorldDemo {
   @Bean 
   public Hello hello(){
      return new Hello();
   }
}

Here is the content of HelloDemo.java file

public class HelloDemo{
   private String message;
   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}
Following is the content of the MainDemo.java file
public class MainDemo {
   public static void main(String[] args) {
      ApplicationContext cnt =  new AnnotationConfigApplicationContext(HelloWorldDemo.class);
   
      Hello hello= cnt.getBean(Hello.class);
      hello.setMessage("Hello!");
      hello.getMessage();
   }
}

Your Message: Hello!

Now, Injecting the Bean Dependencies

@Configuration
public class AppConfigDemo {
   @Bean
   public Fun fun() {
   return new Fun(bar());
   }
   @Bean
   public Foo far() {
      return new Foo();
   }
}

Here, the fun bean receives a reference to foo via the constructor injection.

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button