參考:http://wiki.jikexueyuan.com/project/spring/java-based-configuration.html
@Configuration 和 @Bean 注解
帶有 @Configuration 的注解類表示這個類可以使用 Spring IoC 容器作為 bean 定義的來源。@Bean 注解告訴 Spring,一個帶有 @Bean 的注解方法將返回一個對象,該對象應該被注冊為在 Spring 應用程序上下文中的 bean。最簡單可行的 @Configuration 類如下所示:
1 package org.wzh.di.demo1.congiration; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 6 @Configuration 7 public class HelloWorldConfig { 8 @Bean 9 public HelloWorld helloWorld() { 10 return new HelloWorld(); 11 } 12 }
1 package org.wzh.di.demo1.congiration; 2 3 public class HelloWorld { 4 5 private String message; 6 7 public String getMessage() { 8 return message; 9 } 10 11 public void setMessage(String message) { 12 this.message = message; 13 } 14 15 }
1 package org.wzh.di.demo1.congiration; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 5 6 public class Test { 7 8 public static void main(String[] args) { 9 ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); 10 HelloWorld helloWorld = ctx.getBean(HelloWorld.class); 11 helloWorld.setMessage("Hello World!"); 12 String msg = helloWorld.getMessage(); 13 System.out.println(msg); 14 } 15 16 }
也可以加載其他配置類,這里只寫用法
1 package org.wzh.di.demo1.congiration; 2 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 5 public class Test2 { 6 7 public static void main(String[] args) { 8 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 9 ctx.register(HelloWorldConfig.class); 10 ctx.refresh(); 11 HelloWorld helloWorld = ctx.getBean(HelloWorld.class); 12 helloWorld.setMessage("Hello World 2!"); 13 String msg = helloWorld.getMessage(); 14 System.out.println(msg); 15 } 16 17 }