美文网首页
Spring IOC(一)

Spring IOC(一)

作者: 情天孽海 | 来源:发表于2019-01-25 10:47 被阅读4次

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>
  1. 创建一个接口 UserDao
public interface UserDao {

    public void add();
    public void delete();
    public void update();
    public void find();
}

  1. 实现接口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("查找执行方法.....");
    }
}
  1. 配置:在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>
  1. 使用ClassPathXmlApplicationContext加载
  ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDaoImpl userDao = (UserDaoImpl) classPathXmlApplicationContext.getBean("userDao");
        userDao.add();
        userDao.delete();

相关文章

网友评论

      本文标题:Spring IOC(一)

      本文链接:https://www.haomeiwen.com/subject/yqhmjqtx.html