@Bean

转自http://www.cnblogs.com/bossen/p/5824067.htmlhtml

注解分为两类:java

一、一类是使用Bean,便是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;好比@Autowired , @Resource,能够经过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean;spring

 

二、一类是注册Bean,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一块儿,把对象、属性、方法完美组装。app

 

3、@Bean是啥?测试

 

一、原理是什么?先看下源码中的部份内容:ui

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Indicates that a method produces a bean to be managed  by  the Spring container.
 
  <h3>Overview</h3>
 
  <p>The names and semantics of the attributes to  this  annotation are intentionally
  similar to those of the {@code <bean/>} element  in  the Spring XML schema. For
  example:
 
  <pre  class = "code" >
      @Bean
      public  MyBean myBean() {
          // instantiate and configure MyBean obj
          return  obj;
     }</pre>

  意思是@Bean明确地指示了一种方法,什么方法呢——产生一个bean的方法,而且交给Spring容器管理;从这咱们就明白了为啥@Bean是放在方法的注释上了,由于它很明确地告诉被注释的方法,你给我产生一个Bean,而后交给Spring容器,剩下的你就别管了this

 二、记住,@Bean就放在方法上,就是产生一个Bean,那你是否是又糊涂了,由于已经在你定义的类上加了@Configration等注册Bean的注解了,为啥还要用@Bean呢?这个我也不知道,下面我给个例子,一块儿探讨一下吧:spa

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package  com.edu.fruit;
   //定义一个接口
     public  interface  Fruit<T>{
         //没有方法
}
 
/*
*定义两个子类
*/
package  com.edu.fruit;
      @Configuration
      public  class  Apple  implements  Fruit<Integer>{ //将Apple类约束为Integer类型
 
}
 
package  com.edu.fruit;
      @Configuration
      public  class  GinSeng  implements  Fruit<String>{ //将GinSeng 类约束为String类型
 
}
/*
*业务逻辑类
*/
package  com.edu.service;
        @Configuration
        public  class  FruitService {
           @Autowired
           private  Apple apple;
           @Autowired
           private  GinSeng ginseng;
     //定义一个产生Bean的方法
        @Bean (name= "getApple" )
        public  Fruit<?> getApple(){
        System.out.println(apple.getClass().getName().hashCode);
          System.out.println(ginseng.getClass().getName().hashCode);
        return  new  Apple();
}
}
/*
*测试类
*/
@RunWith (BlockJUnit4ClassRunner. class )
public  class  Config {
     public  Config(){
         super ( "classpath:spring-fruit.xml" );
     }
     @Test
     public  void  test(){
         super .getBean( "getApple" ); //这个Bean从哪来,从上面的@Bean下面的方法中来,返回
                                                           的是一个Apple类实例对象
         
     }
}

从上面的例子也印证了我上面的总结的内容:code

一、凡是子类及带属性、方法的类都注册Bean到Spring中,交给它管理;xml

二、@Bean 用在方法上,告诉Spring容器,你能够从下面这个方法中拿到一个Bean

相关文章
相关标签/搜索