Spring實現無需注解實現自動注入


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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM