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 }
原文地址:https://www.cnblogs.com/lonecloud/p/5789755.html