将service和dao的类交给ioc的容器去做管理,并且使用注解的方式
在resources编写xml文件(创建Spring Config) applicationContext
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 去管理 -->
<context:component-scan base-package="cn.itcast">
<!-- 配置要忽略的注解 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
测试service是否可用,在AccountServiceImpl类前加上@Service(“accountService”)
@Service("accountService")
public class AccountServiceImpl implements AccountService
创建Test包进行测试,正确输出则Spring环境搭建成功(⚠️ 警告问题:只需要把log4j文件导入resources即可,可以忽略)
public class testSpring {
@Test
public void run1() {
//加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//获取对象
AccountService as = (AccountService) ac.getBean("accountService");
//调用方法
as.findAll();
}
}