自動組件掃描
第一步:使用@Component標(biāo)記類,使得spring容器能夠識別為一個組件
@Component public class UserDAO { public void outPut(){ System.out.println("你好,這是一個自動掃描的demo"); }}第二步:在bean配置文件中啟動掃描
<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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.main.autowrite.autoScanning" /></beans>第三步:提取bean并調(diào)用
@Test public void test(){ applicationContext context = new ClassPathXmlApplicationContext("com/main/autowrite/autoScanning/bean.xml"); UserDAO dao = (UserDAO)context.getBean("userDAO"); dao.outPut(); }輸出結(jié)果為:
你好,這是一個自動掃描的demo自定義組件名稱:使用@Service(“value”)
@Service("student") public class User{...} //調(diào)用方法 User user = (User)context.getBean("student");實(shí)際上,可以用以下四種注解來標(biāo)識組件
@Component ——表示自動掃描組件@Service ——表示在業(yè)務(wù)層服務(wù)組件@Controller ——表示在表示層控制器組件@Repository ——表示在持久層DAO組件攔截器
允許特定組件可以通過
<context:component-scan base-package="com.yiibai" > <context:include-filter type="regex" expression="com.yiibai.customer.dao.*DAO.*" /> <context:include-filter type="regex" expression="com.yiibai.customer.services.*Service.*" /> </context:component-scan>說明:上述例子中將允許含有關(guān)鍵字DAO和Service的組件,在spring容器中注冊,其他類型的組件都會被攔截掉
不允許特定組件通過
<context:component-scan base-package="com.yiibai" > <context:exclude-filter type="regex" expression="com.yiibai.customer.dao.*DAO.*" /> </context:component-scan>說明:上述例子中將攔截掉含有關(guān)鍵字DAO的組件,其他則pass
<context:component-scan base-package="com.yiibai.customer" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>說明:不允許含有@Service的組件通過
注意:type為regex是指關(guān)鍵字,type為annoation是指特定注解
新聞熱點(diǎn)
疑難解答