Spring 3 JavaConfigの例
Spring 3、JavaConfig機能はコアSpringモジュールに含まれているため、開発者はBean定義とSpring構成をXMLファイルからJavaクラスに移動できます。
ただし、従来のXMLの方法を使用してBeanと構成を定義することは引き続き許可されており、JavaConfigは単なる別の代替ソリューションです。
SpringコンテナでBeanを定義するには、従来のXML定義とJavaConfigの違いをご覧ください。
Spring XMLファイル:
JavaConfigの同等の構成:
package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.hello.HelloWorld; import com.example.hello.impl.HelloWorldImpl; @Configuration public class AppConfig { @Bean(name="helloBean") public HelloWorld helloWorld() { return new HelloWorldImpl(); } }
Spring JavaConfig Hello World
次に、Spring JavaConfigの完全な例を参照してください。
1. ディレクトリ構造
この例のディレクトリ構造を参照してください。
2. 依存ライブラリ
JavaConfig(@Configuration)を使用するには、CGLIBライブラリを含める必要があります。 依存関係を参照してください:
org.springframework spring-core ${spring.version} org.springframework spring-context ${spring.version} cglib cglib 2.2.2
3. 春豆
シンプルな豆。
package com.example.hello; public interface HelloWorld { void printHelloWorld(String msg); }
package com.example.hello.impl; import com.example.hello.HelloWorld; public class HelloWorldImpl implements HelloWorld { @Override public void printHelloWorld(String msg) { System.out.println("Hello : " + msg); } }
4. JavaConfigアノテーション
@Configuration
で注釈を付けて、これがコアSpring構成ファイルであることをSpringに通知し、@Bean
を介してBeanを定義します。
package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.hello.HelloWorld; import com.example.hello.impl.HelloWorldImpl; @Configuration public class AppConfig { @Bean(name="helloBean") public HelloWorld helloWorld() { return new HelloWorldImpl(); } }
5. それを実行します
JavaConfigクラスにAnnotationConfigApplicationContext
をロードします。
package com.example.core; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.example.config.AppConfig; import com.example.hello.HelloWorld; public class App { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); HelloWorld obj = (HelloWorld) context.getBean("helloBean"); obj.printHelloWorld("Spring3 Java Config"); } }
出力
Hello : Spring3 Java Config
ソースコードをダウンロード
ダウンロード–Spring3-JavaConfig-Example.zip(6 KB)