一、搜索Bean類
爲了不再使用Spring的配置文件來配置任何bean實例,Spring自動搜索某些路徑下的Java類,並將這些java類註冊成Bean實例
Spring提供瞭如下幾個Annotation來標註Spring Bean,目的讓Spring知道應該把哪些Java類當成Bean類處理。
- @Conponent:標註一個普通的Spring Bean 類
- @Controller:標註一個控制器組件類
- @Service:標註一個業務邏輯組件類
- @Repository:標註一個Dao組件類
二、使用實例
package com.home.bean;
/**
* 定義一個接口
*/
public interface Axe {
public String chop();
}
package com.home.bean;
import org.springframework.stereotype.Component;
@Component
public class SteelAxe implements Axe{
public String chop() {
// TODO Auto-generated method stub
return "鋼斧砍柴真的很快";
}
}
package com.home.bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//指定該bean實例的作用域爲prototype,不指定默認爲singleton
@Scope("prototype")
//指定該類作爲spring Bean,Bean實例名爲axe
@Component("stoneAxe")
public class StoneAxe implements Axe{
public String chop() {
// TODO Auto-generated method stub
return "石斧砍柴真的很慢";
}
}
配置文件:
<context:annotation-config/>
<!-- 自動掃描指定包及其子包下的所有bean類 -->
<context:component-scan base-package="com.home.bean">
<!-- 只是以Axe結尾的類當成Spring容器中的bean -->
<!-- type:指定過濾器類型
1.annotation:Annotation過濾器,該過濾器需要指定一個Annotation名,如lee.AnnotationTest
2.assignable:類過濾器,該過濾器直接指定一個java類
3.regex,正則表達式過濾器,指定過濾規則,使用如下
4.aspectJ:AspectJ過濾器,如org.example.*Service+
-->
<context:include-filter type="regex" expression=".*Axe"/>
</context:component-scan>
測試類:
package spring;
import java.util.Arrays;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanTest {
public static void main(String[] args) {
//創建spring容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("Bean實例名稱:"+Arrays.toString(ctx.getBeanDefinitionNames()));
}
}