xml配置
過程:設定自動裝配的包-->使用include-filter過濾type選擇為regex為正規表示式-->expression是表達是式也就是限制條件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 7 <!-- 用於自動裝配 --> 8 <context:component-scan base-package="cn.lonecloud"> 9 <!-- 包含某個包下的Dao層type 型別 regex表示正規表示式 expression 需要設定的限制條件 --> 10 <!-- 使用這個的表示的包下的某些符合該表示式的Dao層可以不用使用註解即可直接使用 --> 11 <context:include-filter type="regex" expression="cn.lonecloud.dao.*Dao.*"/> 12 <context:include-filter type="regex" expression="cn.lonecloud.service.*Service.*"/> 13 <!-- 用於配置在該型別下的類將不被Spring容器註冊 --> 14 <context:exclude-filter type="regex" expression="cn.lonecloud.service.TestService"/> 15 </context:component-scan> 16 17 </beans>
Dao層
1 package cn.lonecloud.dao; 2 3 public class TestDao { 4 public void Test01() { 5 System.out.println("Dao"); 6 } 7 }
Service層
1 package cn.lonecloud.service; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 5 import cn.lonecloud.dao.TestDao; 6 7 public class TestService { 8 9 @Autowired 10 TestDao testDao; 11 12 public void Test01(){ 13 testDao.Test01(); 14 } 15 }
Test層
1 package cn.lonecloud.test; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 import cn.lonecloud.service.TestService; 8 9 public class TestMain { 10 ClassPathXmlApplicationContext xmlApplicationContext=null; 11 @Before 12 public void init(){ 13 xmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 14 } 15 @Test 16 public void Test01(){ 17 TestService testService=xmlApplicationContext.getBean(TestService.class); 18 testService.Test01(); 19 } 20 }