淺談Spring框架注解的用法分析


原文出處: locality

1.@Component是Spring定義的一個通用注解,可以注解任何bean。

2.@Scope定義bean的作用域,其默認作用域是”singleton”,除此之外還有prototype,request,session和global session。


案例:@Component和@Scope用法分析:

BeanAnnotation類:

 1 @Scope
 2 @Component
 3 public class BeanAnnotation {
 4  
 5     public void say(String arg) {
 6         System.out.println("BeanAnnotation : " + arg);
 7     }
 8  
 9     public void myHashCode() {
10         System.out.println("BeanAnnotation : " + this.hashCode());
11     }
12  
13 }

junit4測試類→TestBeanAnnotation類:

 1 @RunWith(BlockJUnit4ClassRunner.class)
 2 public class TestBeanAnnotation extends UnitTestBase {
 3  
 4     public TestBeanAnnotation() {
 5         super("classpath*:spring-beanannotation.xml");
 6     }
 7  
 8     @Test
 9     public void testSay() {
10         BeanAnnotation bean = super.getBean("beanAnnotation");
11         bean.say("This is test.");
12     }
13  
14     @Test
15     public void testScpoe() {
16         BeanAnnotation bean = super.getBean("beanAnnotation");
17         bean.myHashCode();
18         bean = super.getBean("beanAnnotation");
19         bean.myHashCode();
20     }
21  
22 }

Spring配置文件→spring-beanannotation.xml:

1 <context:component-scan base-package="com.beanannotation"></context:component-scan>

我們先從Spring配置文件分析,base-package="com.beanannotation"說明我們只處理這個包名下面的注解。

然后分析BeanAnnotation類,有一個say的方法。假設我們不清楚這是一個什么類型(注:Service或者DAO)的類,我們可以用一個通用的注解@Component。

最后分析TestBeanAnnotation類,testSay方法里super.getBean("beanAnnotation")是從IOC的容器中取到這個bean,並調用bean的say方法。

提出問題的時間到了,當我們super.getBean的時候是通過bean的id從IOC容器中獲取的,那么這個id是什么呢?因為在我們添加@Component到BeanAnnotation類上的時候,默認的id為beanAnnotation。如果指定了@Component的名稱,譬如指定為@Component(”bean”)的時候,在單元測試的時候就必須把super.getBean得到的id與之相對應才能測試成功。

在這里我把@Scope注解單獨分離出來分析,在TestBeanAnnotation類里面有一個testScpoe方法。在BeanAnnotation類里面有一個myHashCode方法,可能大家有些疑惑,為什么要用this.hashCode()?因為@Scope指定的是bean的作用域,為了保證測試類的結果准確明了,所以采用哈希碼值來判斷是否為同一個對象。


3.@Repository、@Service、@Controller是更具有針對性的注解。
PS:這里我們需要明白這三個注解是基於@Component定義的注解哦:
①、@Repository通常用於注解DAO類,也就是我們常說的持久層。
②、@Service通常用於注解Service類,也就是服務層。
③、@Controller通常用於Controller類,也就是控制層(MVC)。

4.@Autowired理解為“傳統”的setter方法,可以用在setter方法上,也可以用在構造器或者成員變量,能夠進行Spring Bean的自動裝配。


案例:@Autowired用法分析一:

Spring配置文件→spring-beanannotation.xml:

1 <context:component-scan base-package="com.beanannotation"></context:component-scan>

SimpleMovieLister類:

 1 public class SimpleMovieLister {
 2  
 3     private MovieFinder movieFinder;
 4  
 5     @Autowired(required=false)
 6     public void setMovieFinder(MovieFinder movieFinder) {
 7         this.movieFinder = movieFinder;
 8     }
 9  
10 }

在默認的情況下,如果找不到合適的bean將會導致autowiring失敗拋出異常,我們可以將@Autowired注解在這個set方法上,標記required=false來避免。但是,這不是一個必須的,如果找不到movieFinder的實例,是不會拋出異常的,只有在使用的時候發現movieFinder為null,在這種情況下,就要求我們在使用的時候,首先判斷movieFinder是不是為null,如果是就會報空指針異常 。

值得注意的是,我們知道每個類可以有很多個構造器,但是在使用@Autowired的時候,有且只能有一個構造器能夠被標記為required=true(注:required的默認值為false)。


案例:@Autowired用法分析二:

BeanImplOne類:

1 @Order
2 @Component
3 public class BeanImplOne implements BeanInterface {
4  
5 }

BeanImplTwo類:

1 @Order
2 @Component
3 public class BeanImplTwo implements BeanInterface {
4  
5 }

BeanInterface類:

1 public interface BeanInterface {
2  
3 }

BeanInvoker類:

 1 @Component
 2 public class BeanInvoker {
 3  
 4     @Autowired
 5     private List<BeanInterface> list;
 6  
 7     @Autowired
 8     private Map<String, BeanInterface> map;
 9  
10     public void say() {
11         if (null != list && 0 != list.size()) {
12             for (BeanInterface bean : list) {
13                 System.out.println(bean.getClass().getName());
14             }
15         } else {
16             System.out.println(" list is null !");
17         }
18  
19         if (null != map && 0 != map.size()) {
20             for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
21                 System.out.println(entry.getKey() + "      " + entry.getValue().getClass().getName());
22             }
23         } else {
24             System.out.println("map is null !");
25         }
26     }
27 }

測試類TestInjection:

 1 @RunWith(BlockJUnit4ClassRunner.class)
 2 public class TestInjection extends UnitTestBase {
 3  
 4     public TestInjection() {
 5         super("classpath:spring-beanannotation.xml");
 6     }
 7  
 8     @Test
 9     public void testMultiBean() {
10         BeanInvoker invoker = super.getBean("beanInvoker");
11         invoker.say();
12     }
13  
14 }

首先,我們清楚BeanImplOne類和BeanImplTwo類是實現了BeanInterface接口的,在BeanInvoker類里面我們定義了list和map,我們通過@Autowired注解把BeanImplOne類和BeanImplTwo類注解進入其中。那么怎么證實是@Autowired注解把這兩個類注入到list或者map中的呢?那么請看if循環語句和foreach循環打印,通過這個邏輯判斷,如果能夠打印出BeanImplOne類和BeanImplTwo類的路徑名,就說明這樣是可以的。如果有些小伙伴可能不信,那么可以試着不使用@Autowired注解,看結果怎么樣。

測試類沒有什么好說的,各位小伙伴有沒有注意到@Order注解呢?這里需要解釋的就是,如果在@Order注解里面輸入執行的數字,比如1或者2,那么打印出來的路徑名就會按順序,也就是說通過指定@Order注解的內容可以實現優先級的功能。


5.@ImportResource注解引入一個資源,對應一個xml文件
6.@Value注解從資源文件中,取出它的key並賦值給當前類的成員變量


案例:@ImportResource和@Value用法分析:

MyDriverManager類:

1 public class MyDriverManager {
2  
3     public MyDriverManager(String url, String userName, String password) {
4         System.out.println("url : " + url);
5         System.out.println("userName: " + userName);
6         System.out.println("password: " + password);
7     }
8  
9 }

config.xml:

1 <context:property-placeholder location="classpath:/config.properties"/>

StoreConfig類:

 1 @Configuration
 2 @ImportResource("classpath:config.xml")
 3 public class StoreConfig {
 4  
 5     @Value("${jdbc.url}")
 6     private String url;
 7  
 8     @Value("${jdbc.username}")
 9     private String username;
10  
11     @Value("${jdbc.password}")
12     private String password;
13  
14     @Bean
15     public MyDriverManager myDriverManager() {
16         return new MyDriverManager(url, username, password);
17     }

這個案例我們使用注解配置jdbc數據庫的連接,首先創建一個內含構造器的MyDriverManager類,然后配置config.xml里面的資源文件路徑,以便@ImportResource注解獲取,最后配置StoreConfig類。(注意url、username、password也必須要和數據庫的保持一致哦)

詳解StoreConfig類:首先我們定義三個成員變量,然后給每一個成員變量打上一個@value注解,注意@value里面的內容一定是資源文件里面的key值。這里的@ImportResource注解就是指明一個資源文件,在這個資源文件里面獲取到對應的數據。那么@Configuration注解是用來干嘛的呢?為什么不用@Component注解呢?其實是這樣的,@Component注解用於將所標注的類加載到 Spring 環境中,這時候是需要配置component-scan才能使用的,而@Configuration注解是Spring 3.X后提供的注解,它用於取代XML來配置 Spring。


7.@Bean注解用來標識配置和初始化一個由SpringIOC容器管理的新對象的方法,類似XML中配置文件的<bean/>

ps:默認的@Bean注解是單例的,那么有什么方式可以指定它的范圍呢?所以這里才出現了@Scope注解

8.@Scope注解,在@Scope注解里面value的范圍和Bean的作用域是通用的,proxyMode的屬性是采用哪一種的單例方式(一種是基於接口的注解,一種是基於類的代理)


案例:@Bean和@Scope用法分析:

 1 @Bean
 2 @Scope(value ="session",proxyMode = "scopedProxyMode.TARGET_CLASS")
 3 public UserPreferences userPreferences(){
 4     return new userPreferences();
 5 }
 6  
 7 @Bean
 8 public service userService(){
 9     UserService service =new SimpleUserService();
10     service.setUserPreferences(userPreferences);
11     return service;
12 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM