Spring中Bean及@Bean的理解

Bean在Spring和SpringMVC中無所不在,將這個概念內化很重要,下面分享一下我的想法:

 

一、Bean是啥

1、Java面向對象,對象有方法和屬性,那麼就需要對象實例來調用方法和屬性(即實例化);

 

2、凡是有方法或屬性的類都需要實例化,這樣才能具象化去使用這些方法和屬性;

 

3、規律:凡是子類及帶有方法或屬性的類都要加上註冊Bean到Spring IoC的註解

 

4、把Bean理解爲類的代理或代言人(實際上確實是通過反射、代理來實現的),這樣它就能代表類擁有該擁有的東西了

 

5、我們都在微博上@過某某,對方會優先看到這條信息,並給你反饋,那麼在Spring中,你標識一個@符號,那麼Spring就會來看看,並且從這裏拿到一個Bean或者給出一個Bean

二、註解分爲兩類:

1、一類是使用Bean,即是把已經在xml文件中配置好的Bean拿來用,完成屬性、方法的組裝;比如@Autowired , @Resource,可以通過byTYPE(@Autowired)、byNAME(@Resource)的方式獲取Bean;

 

2、一類是註冊Bean,@Component , @Repository , @ Controller , @Service , @Configration這些註解都是把你要實例化的對象轉化成一個Bean,放在IoC容器中,等你要用的時候,它會和上面的@Autowired , @Resource配合到一起,把對象、屬性、方法完美組裝。

 

三、@Bean是啥?

 

1、原理是什麼?先看下源碼中的部分內容:

 

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容器,剩下的你就別管了

 2、記住,@Bean就放在方法上,就是產生一個Bean,那你是不是又糊塗了,因爲已經在你定義的類上加了@Configration等註冊Bean的註解了,爲啥還要用@Bean呢?這個我也不知道,下面我給個例子,一起探討一下吧:

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類實例對象
         
    }
}

從上面的例子也印證了我上面的總結的內容:

1、凡是子類及帶屬性、方法的類都註冊Bean到Spring中,交給它管理;

2、@Bean 用在方法上,告訴Spring容器,你可以從下面這個方法中拿到一個Bean

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章