English 中文(简体)
Spring - Java Based Configuration
  • 时间:2024-12-22

Spring - Java Based Configuration


Previous Page Next Page  

So far you have seen how we configure Spring beans using XML configuration file. If you are comfortable with XML configuration, then it is really not required to learn how to proceed with Java-based configuration as you are going to achieve the same result using either of the configurations available.

Java-based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained in this chapter.

@Configuration & @Bean Annotations

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring apppcation context. The simplest possible @Configuration class would be as follows −

package com.tutorialspoint;
import org.springframework.context.annotation.*;

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

The above code will be equivalent to the following XML configuration −

<beans>
   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>

Here, the method name is annotated with @Bean works as bean ID and it creates and returns the actual bean. Your configuration class can have a declaration for more than one @Bean. Once your configuration classes are defined, you can load and provide them to Spring container using AnnotationConfigApppcationContext as follows −

pubpc static void main(String[] args) {
   ApppcationContext ctx = new AnnotationConfigApppcationContext(HelloWorldConfig.class);
   
   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}

You can load various configuration classes as follows −

pubpc static void main(String[] args) {
   AnnotationConfigApppcationContext ctx = new AnnotationConfigApppcationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

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

Example

Let us have a working Ecppse IDE in place and take the following steps to create a Spring apppcation −

Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring pbraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar pbrary which can be downloaded from asm.ow2.org.
4 Create Java classes HelloWorldConfig, HelloWorld and MainApp under the com.tutorialspoint package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the apppcation as explained below.

Here is the content of HelloWorldConfig.java file

package com.tutorialspoint;
import org.springframework.context.annotation.*;

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

Here is the content of HelloWorld.java file

package com.tutorialspoint;

pubpc class HelloWorld {
   private String message;

   pubpc void setMessage(String message){
      this.message  = message;
   }
   pubpc void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Following is the content of the MainApp.java file

package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.annotation.*;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext ctx = 
         new AnnotationConfigApppcationContext(HelloWorldConfig.class);
   
      HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
      helloWorld.setMessage("Hello World!");
      helloWorld.getMessage();
   }
}

Once you are done creating all the source files and adding the required additional pbraries, let us run the apppcation. You should note that there is no configuration file required. If everything is fine with your apppcation, it will print the following message −

Your Message : Hello World!

Injecting Bean Dependencies

When @Beans have dependencies on one another, expressing that the dependency is as simple as having one bean method calpng another as follows −

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
pubpc class AppConfig {
   @Bean
   pubpc Foo foo() {
      return new Foo(bar());
   }
   @Bean
   pubpc Bar bar() {
      return new Bar();
   }
}

Here, the foo bean receives a reference to bar via the constructor injection. Now let us look at another working example.

Example

Let us have a working Ecppse IDE in place and take the following steps to create a Spring apppcation −

Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring pbraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar pbrary which can be downloaded from asm.ow2.org.
4 Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under the com.tutorialspoint package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the apppcation as explained below.

Here is the content of TextEditorConfig.java file

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
pubpc class TextEditorConfig {
   @Bean 
   pubpc TextEditor textEditor(){
      return new TextEditor( spellChecker() );
   }

   @Bean 
   pubpc SpellChecker spellChecker(){
      return new SpellChecker( );
   }
}

Here is the content of TextEditor.java file

package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;

   pubpc TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   pubpc void spellCheck(){
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java

package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file

package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.annotation.*;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext ctx = 
         new AnnotationConfigApppcationContext(TextEditorConfig.class);

      TextEditor te = ctx.getBean(TextEditor.class);
      te.spellCheck();
   }
}

Once you are done creating all the source files and adding the required additional pbraries, let us run the apppcation. You should note that there is no configuration file required. If everything is fine with your apppcation, it will print the following message −

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelpng.

The @Import Annotation

The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows −

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

You can import above Bean declaration in another Bean Declaration as follows −

@Configuration
@Import(ConfigA.class)
pubpc class ConfigB {
   @Bean
   pubpc B b() {
      return new B(); 
   }
}

Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be suppped as follows −

pubpc static void main(String[] args) {
   ApppcationContext ctx = new AnnotationConfigApppcationContext(ConfigB.class);
   
   // now both beans A and B will be available...
   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);
}

Lifecycle Callbacks

The @Bean annotation supports specifying arbitrary initiapzation and destruction callback methods, much pke Spring XML s init-method and destroy-method attributes on the bean element −

pubpc class Foo {
   pubpc void init() {
      // initiapzation logic
   }
   pubpc void cleanup() {
      // destruction logic
   }
}
@Configuration
pubpc class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   pubpc Foo foo() {
      return new Foo();
   }
}

Specifying Bean Scope

The default scope is singleton, but you can override this with the @Scope annotation as follows −

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