Spring-Java 기반 구성

지금까지 XML 구성 파일을 사용하여 Spring Bean을 구성하는 방법을 보았습니다. XML 구성에 익숙하다면 사용 가능한 구성 중 하나를 사용하여 동일한 결과를 얻을 수 있으므로 Java 기반 구성을 진행하는 방법을 배울 필요가 없습니다.

Java 기반 구성 옵션을 사용하면이 장에서 설명하는 몇 가지 Java 기반 주석을 사용하여 XML없이 대부분의 Spring 구성을 작성할 수 있습니다.

@ 구성 및 @Bean 주석

클래스에 주석 달기 @Configuration클래스가 Spring IoC 컨테이너에서 Bean 정의의 소스로 사용될 수 있음을 나타냅니다. 그만큼@Bean어노테이션은 @Bean으로 어노테이션 된 메소드가 Spring 애플리케이션 컨텍스트에서 Bean으로 등록되어야하는 오브젝트를 리턴 할 것이라고 Spring에 알려줍니다. 가장 간단한 @Configuration 클래스는 다음과 같습니다.

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

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

위의 코드는 다음 XML 구성과 동일합니다.

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

여기서 메서드 이름은 @Bean으로 주석 처리되어 빈 ID로 작동하며 실제 빈을 생성하고 반환합니다. 구성 클래스는 둘 이상의 @Bean에 대한 선언을 가질 수 있습니다. 구성 클래스가 정의되면 다음과 같이 AnnotationConfigApplicationContext 를 사용하여 Spring 컨테이너에로드하고 제공 할 수 있습니다.

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

다음과 같이 다양한 구성 클래스를로드 할 수 있습니다.

public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

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

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

작동하는 Eclipse IDE를 준비하고 다음 단계를 수행하여 Spring 애플리케이션을 작성해 보겠습니다.

단계 기술
1 이름이 SpringExample 인 프로젝트를 만들고 아래에 com.tutorialspoint 패키지를 만듭니다 .src 생성 된 프로젝트의 폴더.
2 Spring Hello World 예제 장에 설명 된대로 Add External JARs 옵션을 사용하여 필요한 Spring 라이브러리를 추가하십시오 .
자바 기반의 주석을 사용하고 있기 때문에, 그래서 당신은 또한 추가 할 필요가 CGLIB.jar을 자바 설치 디렉토리에서 ASM.jar의 에서 다운로드 할 수 있습니다 라이브러리 asm.ow2.org .
4 com.tutorialspoint 패키지 아래에 Java 클래스 HelloWorldConfig , HelloWorldMainApp을 만듭니다 .
5 마지막 단계는 모든 Java 파일과 Bean 구성 파일의 내용을 만들고 아래 설명 된대로 응용 프로그램을 실행하는 것입니다.

내용은 다음과 같습니다. HelloWorldConfig.java 파일

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

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

내용은 다음과 같습니다. HelloWorld.java 파일

package com.tutorialspoint;

public class HelloWorld {
   private String message;

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

다음은의 내용입니다 MainApp.java 파일

package com.tutorialspoint;

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

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

모든 소스 파일을 만들고 필요한 추가 라이브러리를 추가했으면 응용 프로그램을 실행하겠습니다. 구성 파일이 필요하지 않습니다. 응용 프로그램에 문제가 없으면 다음 메시지가 인쇄됩니다.

Your Message : Hello World!

빈 의존성 주입

@Beans가 서로 종속성을 가질 때 종속성이 다음과 같이 하나의 bean 메소드가 다른 메소드를 호출하는 것처럼 간단하다는 것을 표현합니다.

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

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

여기서 foo 빈은 생성자 주입을 통해 bar에 대한 참조를받습니다. 이제 다른 작동 예를 살펴 보겠습니다.

작동하는 Eclipse IDE를 준비하고 다음 단계를 수행하여 Spring 애플리케이션을 작성해 보겠습니다.

단계 기술
1 이름이 SpringExample 인 프로젝트를 만들고 아래에 com.tutorialspoint 패키지를 만듭니다 .src 생성 된 프로젝트의 폴더.
2 Spring Hello World 예제 장에 설명 된대로 Add External JARs 옵션을 사용하여 필요한 Spring 라이브러리를 추가하십시오 .
자바 기반의 주석을 사용하고 있기 때문에, 그래서 당신은 또한 추가 할 필요가 CGLIB.jar을 자바 설치 디렉토리에서 ASM.jar의 에서 다운로드 할 수 있습니다 라이브러리 asm.ow2.org .
4 com.tutorialspoint 패키지 아래에 Java 클래스 TextEditorConfig , TextEditor , SpellCheckerMainApp만듭니다 .
5 마지막 단계는 모든 Java 파일과 Bean 구성 파일의 내용을 만들고 아래 설명 된대로 응용 프로그램을 실행하는 것입니다.

내용은 다음과 같습니다. TextEditorConfig.java 파일

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

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

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

내용은 다음과 같습니다. TextEditor.java 파일

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;

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

다음은 다른 종속 클래스 파일의 내용입니다. SpellChecker.java

package com.tutorialspoint;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

다음은의 내용입니다 MainApp.java 파일

package com.tutorialspoint;

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

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext ctx = 
         new AnnotationConfigApplicationContext(TextEditorConfig.class);

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

모든 소스 파일을 만들고 필요한 추가 라이브러리를 추가했으면 응용 프로그램을 실행하겠습니다. 구성 파일이 필요하지 않습니다. 응용 프로그램에 문제가 없으면 다음 메시지가 인쇄됩니다.

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Import 주석

그만큼 @Import주석을 사용하면 다른 구성 클래스에서 @Bean 정의를로드 할 수 있습니다. 다음과 같이 ConfigA 클래스를 고려하십시오-

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

다음과 같이 다른 Bean 선언에서 Bean 선언을 가져올 수 있습니다.

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

이제 컨텍스트를 인스턴스화 할 때 ConfigA.class와 ConfigB.class를 모두 지정할 필요없이 다음과 같이 ConfigB 만 제공하면됩니다.

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

수명주기 콜백

@Bean 어노테이션은 빈 요소에 대한 Spring XML의 init-method 및 destroy-method 속성과 같이 임의의 초기화 및 소멸 콜백 메소드 지정을 지원합니다.

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

빈 범위 지정

기본 범위는 싱글 톤이지만 다음과 같이 @Scope 주석으로이를 재정의 할 수 있습니다.

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