Spring实现无需注解实现自动注入

时间:2023-03-09 17:53:05
Spring实现无需注解实现自动注入

xml配置

过程:设置自动装配的包-->使用include-filter过滤type选择为regex为正则表达式-->expression是表达是式也就是限制条件

 <?xml version="1.0" encoding="UTF-8"?>
<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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 用于自动装配 -->
<context:component-scan base-package="cn.lonecloud">
<!-- 包含某个包下的Dao层type 类型 regex表示正则表达式 expression 需要设置的限制条件 -->
<!-- 使用这个的表示的包下的某些符合该表达式的Dao层可以不用使用注解即可直接使用 -->
<context:include-filter type="regex" expression="cn.lonecloud.dao.*Dao.*"/>
<context:include-filter type="regex" expression="cn.lonecloud.service.*Service.*"/>
<!-- 用于配置在该类型下的类将不被Spring容器注册 -->
<context:exclude-filter type="regex" expression="cn.lonecloud.service.TestService"/>
</context:component-scan> </beans>

Dao层

 package cn.lonecloud.dao;

 public class TestDao {
public void Test01() {
System.out.println("Dao");
}
}

Service层

 package cn.lonecloud.service;

 import org.springframework.beans.factory.annotation.Autowired;

 import cn.lonecloud.dao.TestDao;

 public class TestService {

     @Autowired
TestDao testDao; public void Test01(){
testDao.Test01();
}
}

Test层

 package cn.lonecloud.test;

 import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.lonecloud.service.TestService; public class TestMain {
ClassPathXmlApplicationContext xmlApplicationContext=null;
@Before
public void init(){
xmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void Test01(){
TestService testService=xmlApplicationContext.getBean(TestService.class);
testService.Test01();
}
}