@Configuration & @Bean

Ref:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html

https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch03.html

Khi bạn khai báo 1 class với Annotation @Configuration đồng nghĩa với bạn nói với Spring rằng hãy coi class này như là 1 trong những nguồn khởi tạo Bean nhé 

Nó giống như là 1 file xml mà khai báo các bean trong đó.

Vậy các bean khai báo thế nào trong class này

Cách khai báo là bạn dùng @Bean để khai báo các phương thức trả về các đối tượng Bean, các thể hiện này sẽ được đăng ký vào ApplicationContext

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

Đoạn code trên nó tương đương với
<beans>
   <bean id = "helloWorld" class = "com.mp.HelloWorld" />
</beans>




Dưới đây là một ví dụ khác về cách tiêm sự phụ thuộc vào bean

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

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

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}
public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}


Thay đổi scope cho Bean sang prototype

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

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch