Spring

Spring - Java Based Configuration

Spring - Java Based Configuration

Java-based design alternative empowers you to compose the greater part of your Spring setup without XML, however with the assistance of few Java-based comments clarified in this section. 

@Configuration and @Bean Annotations 

Explaining a class with the @Configuration demonstrates that the Spring IoC compartment can utilize the class as a wellspring of bean definitions. The @Bean comment lets Spring know that a technique clarified with @Bean will return an item that should be enrolled as a bean in the Spring application setting.

package demo;

import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

Injecting Bean Dependencies

package demo;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {
   @Bean
   public xy() {
      return new x(bar());
   }
   @Bean
   public Bar bar() {
      return new Bar();
   }
}

The @Import Annotation

@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A(); 
   }
}

Lifecycle Callbacks

public class x {
   public void init() {
      // initialization logic
   }
   public void cleanup() {
      // destruction logic
   }
}
@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public xy() {
      return new x();
   }
}

Specifying Bean Scope

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}