idea使用maven工程创建Spring项目
1. 导入maven依赖
<!--引入Spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--Spring 注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<!--Spring AOP-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2. 编写resource文件
命名为: applicationContext.xml
详细说明
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
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-4.0.xsd">
<!--扫描包下所有的类,用于注解操作-->
<context:component-scan base-package="com.c21w"></context:component-scan>
<!--把对象的创建交给Spring来管理-->
<!--id 要实现的接口名-->
<!--class 要实现的实体类-->
<bean id="FindUserDao" class="com.c21w.dao.impl.FindUserDaoImpl"></bean>
</beans>
3. 读取配置文件
1. 通过 ApplicationContext 接口接收(饿汉式,读取配置文件后立即创建对象,且每个对象只会生成一次,单例模式)
2. 通过 BeanFactory 接口接收(懒汉式,读取配置文件后只有用到的时候才创建对象,每次使用都会创建对象,多例模式)
//1. ClassPathXmlApplicationContext 可以加载类路径下的配置文件,要求配置文件必须在类路径下。
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. FileSystemXmlApplicationContext 可以加载磁盘任意路径下的配置文件
ApplicationContext ac = new FileSystemXmlApplicationContext("XXXX");
//3. AnnotationConfigApplicationContext 用于读取注解创建容器
ApplicationContext ac = new AnnotationConfigApplicationContext(Class<T>...clazz);
4. 获取对象
//获取配置文件信息
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 根据id获取对象
FindUserDao user = ac.getBean("FindUserDao",FindUserDao.class);