來源:http://blog.163.com/qqabc20082006@126/blog/static/2292852520091128103316534/
Spring的組件自動掃描機制
2009-12-28 10:33:16| 分類: Spring|字號 訂閱
Spring將所有的bean都納入到IOC中創建、管理和維護。對於大型的項目而言,項目中會有成百上千個bean,如果我們都在配置文件中配置,那麼我們就會增加配置文件的體積,顯得過於臃腫,過於龐大,查找維護起來也不太方便。
在Spring2.5中引入了組件自動掃描機制,通過在classpath自動掃描的方式把組件納入到Spring容器中。這大大減少了程序員在配置XML文件上的時間,使得配置文件顯得乾淨,整潔,便於維護。
這種機制的工作步驟是:
1.配置需要掃描的類;
2.在需要被納入Spring容器的類上加上相應的註解;
3.Spring在類路徑下尋找標註了註解的類,並把這些類納入Spring容器中管理。
它的作用是和在XML文件中使用<bean>節點配置組件是一樣的。
自動掃描組件的使用
第一步:配置applicationContext.xml文件;如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<!-- 打開Spring組件自動掃面,並配置要掃描的基本包 -->
<context:component-scan base-package="com.springtest"></context:component-scan>
</beans>
注:<context:component-scan>節點用於通知Spring容器掃描組件,base-package屬性用於指定將要被掃描的組件所在的包名稱。
第二步:爲需要被掃描的類添加相應的註解;註解的類型有以下幾種:
· @Service 用於標註業務層組件;
· @Repository 用於標註數據訪問層組件;
· @Controller 用於標註控制層組件(如:Struts中的action)
· @Component 表示泛型組件,當組件不好歸類的時候,我們可以使用這個組件進行註解。
第三步:當爲類添加完成註解後,我們需要測試相應的組件是否被納入Spring容器,所以我們需要測試組件是否被掃描;如下:
@Test
public void testAddUser()
{
UserBiz userBiz = (UserBiz)context.getBean("userBizImpl");
System.out.println(userBiz);
}
如果輸出不爲空,則說明測試類已經被掃描並且納入了Spring容器。
細節問題總結:
1.當我們進行測試時,用ApplicationContext對象的getBean()方法尋找組件。在之前的配置文件中我們會用<bean>標籤的id屬性去定義,在使用註解後怎樣獲得組建的id呢?
在這種情況下,Spring會將被標註註解的類名拿到,然後再將該類名的第一個字母變爲小寫,放到getBean()方法中。如:UserBizImpl類的組件Id就會是userBizImpl,獲取時爲context.getBean("userBizImpl");
那麼,我們在使用註解時可以自定義組件的Id嗎?
當然可以。我們需要在爲相應的類添加註解時,在註解之後添加自定義的類名,例如:
@Service("userBiz")
public class UserBizImpl implements UserBiz {
……
}
當我們在獲取該組件時,爲context.getBean("userBiz);
2.在配置文件中我們可以對組件(bean)的作用域範圍進行設置,它的默認值是單例模式,那麼在添加註解的情況下,我們怎樣設置組件的作用域範圍呢?
我們可以直接在爲類添加註解的同時,運用另一個註解@Scope("prototype")來設置,如下
@Service("userBiz")@Scope("prototype")
public class UserBizImpl implements UserBiz {
……
}
3.在使用註解時,爲組件設置初始化和銷燬方法:
在添加註解的相應的類中,如果想初始化或銷燬某個方法,我們可以直接在方法上添加註解,如下:
@PostConstruct
public void addItem() {
System.out.println("初始化方法");
}
@PreDestroy
public void testItem() {
System.out.println("釋放資源");
}
4.在使用Spring自動掃描組件後,怎樣進行依賴注入?
運用註解@Resource和@Autowired,併爲依賴對象設置名稱,例如:
@Resource(name="userDao")
private UserDAO userDao = null;
首先它會根據名稱去找Spring自動掃描的並加入到Spring容器的組件(bean),如果有相同的名稱,則進行依賴注入,如果沒有相同的名稱。則會根據類型區尋找組件。
<context:component-scan base-package="com.mycompany">
<context:include-filter type="regex" expression="com\..mycompany\..service\...*" />
<context:exclude-filter type="aspectj" expression="com.mycompany.util..*" />
</context:component-scan>
當有<context:component-scan />後,就可以將<context:annotaion-config />移除了。