1、搜索Bean類
在不實用Spring配置文件來配置任何Bean實例,那么我們只能指望Spring會自動搜索某些路徑下的Java類,並將這些java類注冊為Bean實例。
Spring會合適的將顯示指定路徑下的類全部注冊成Spring Bean。 Spring通過使用特殊的Annotation來標注Bean類。
>@Component :標注一個普通的Spring Bean類。
>@Controller : 標注一個控制器組件類。
>@Service: 標注一個業務邏輯組件類。
>@Repository : 標注一個DAO組件類。
使用@Component 來標注一個類:
package org.service.imp; import org.service.Person; import org.springframework.stereotype.*; @Component public class Chinese implements Person { public String sayHello(String name) { // TODO Auto-generated method stub return name + ":你好!"; } public void eat(String food) { // TODO Auto-generated method stub System.out.println(”我喜歡吃:“+food) ; } }
接下來需要在Spring的配置文件中指定搜索路徑,Spring將會自動搜索該路徑下的所有JAva類,並根據這些類創建Bean實例:
<?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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自動搜索指定包及其子包下的所有Bean類--> <context:component-scan base-package="org.service"> </context:component-scan> </beans>
主程序:
package org.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { //創建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 獲取Spring 容器中的所有Bean實例的名 System.out.println("---------------------" +java.util.Arrays.toString(ctx.getBeanDefinitionNames())) ; } }
通過運行主程序;可以得到 Spring中的Bean實例的名字是:chinese。Bean實例的名字默認是Bean類的首字母小寫,其他地方不變。當然,Spring也允許在使用@Component 標注時指定Bean實例的名稱。格式如:@Component(”Bean實例名字")
在默認情況下,Spring會自動搜索所有以@Component、@Controller 、@Service 和 @Repository 標注的Java類,並將他們當作Spring Bean來處理。
我們還可以通過為<component-scan .. /> 元素添加 <include-filter .. /> 或 <exclude-filter ../>子元素來指定Spring Bean類 , 只要位於指定的路徑下的Java類滿足這種重櫃子,即使Java類沒有使用Annotation 標注,Spring一樣可以把它們當成 Bean類來處理。
<include-filter ... /> 元素使用與指定滿足該規則的Java類 會被當成Bean類,而<exclude-filter .../>相反。
> type : 指定過濾器類型。
> expression : 指定過濾器所需要的表達式。
Spring 內建支持如下過濾器。
> annotation : Annotation 過濾器 ,該過濾器需要指定一個Annotation名.
> assignable : 類名過濾器, 該過濾器直接指定一個Java類
> regex : 正則表達式過濾器,該過濾器指定一個正則表達式 , 匹配該正則表達式的Java類將滿足過濾規則。
> aspectj : AspectJ過濾器。
2、指定Bean的作用域:
采用零配置方式來管理Bean 實例時,可以使用@Scope Annotation 在指定Bean 的作用域。
3、使用@Resource配置依賴:
@Resource 有一個name屬性,在默認情況下,Spring將這個值解釋為需要被注入的Bean實例的名字。相當於<property../>元素的 ref 屬性的效果 。
4、使用@PostConstruct 和 @PreDestroy 制定生命周期行為
前者是修飾的方法是Bean的初始化方法,后者修飾的方法是Bean 銷毀之前的方法。這與Spring 提供的<bean .. /> 元素指定的 init-method 、destroy-method 屬性的作用差不多。