1.2 Spring快速入门

步骤分析
1. 创建java项目,导入spring开发基本坐标
2. 编写Dao接口和实现类
3. 创建spring核心配置文件
4. spring配置文件中配置 UserDaoImpl
5. 使用spring相关API获得Bean实例

1)创建java项目,导入spring开发基本坐标

 1 <dependencies>
 2   <dependency>
 3     <groupId>org.springframework</groupId>
 4     <artifactId>spring-context</artifactId>
 5     <version>5.1.5.RELEASE</version>
 6   </dependency>
 7     <dependency>
 8       <groupId>junit</groupId>
 9       <artifactId>junit</artifactId>
10       <version>4.12</version>
11     </dependency>
12 </dependencies>

 

2)编写Dao接口和实现类

1 public interface UserDao {
2     public void save();
3 } 
4 public class UserDaoImpl implements UserDao { 5 public void save() { 6   System.out.println("保存成功了..."); 7 } 8 }

 

 

3)创建spring核心配置文件

<?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">
</beans>

 

4)在spring配置文件中配置 UserDaoImpl

<beans ...>
  <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"></bean>
</beans>

 

5)使用spring相关API获得Bean实例

public class UserTest {
  @Test
  public void testSave() throws Exception {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    userDao.save();
  }
}

 

posted on 2021-01-21 19:06  louis_w  阅读(70)  评论(0编辑  收藏  举报

导航