首页 > 代码库 > Spring--@configuration 和 @Bean

Spring--@configuration 和 @Bean

参考: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 }

 

Spring--@configuration 和 @Bean