1、配置Spring需要的依赖
创建maven项目,下pop.xml中加入以下配置
<!--spring核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
- 创建一个接口 UserDao
public interface UserDao {
public void add();
public void delete();
public void update();
public void find();
}
- 实现接口UserDao
public class UserDaoImpl implements UserDao {
public void add() {
System.out.println("增加执行方法.....");
}
public void delete() {
System.out.println("删除执行方法.....");
}
public void update() {
System.out.println("修改执行方法.....");
}
public void find() {
System.out.println("查找执行方法.....");
}
}
-
配置:在resources目录下创建applicationContext.xml(文件名随意)
image.png
添加“ <bean id="userDao" class="com.laotunong.spring.UserDaoImpl"/>”
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.laotunong.spring.UserDaoImpl"/>
</beans>
- 使用ClassPathXmlApplicationContext加载
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDaoImpl userDao = (UserDaoImpl) classPathXmlApplicationContext.getBean("userDao");
userDao.add();
userDao.delete();
网友评论