將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();
}
}