Spring的IoC入门案例

1、创建工程,导入坐标

1.1 创建工程

image.png

1.2 导入坐标



    4.0.0

    org.example
    spring_01_ioc_xml
    1.0-SNAPSHOT

    jar

    
        
            org.springframework
            spring-context
            5.0.2.RELEASE
        
    

2、创建三层对象

2.1 controller

public class UserController {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = ac.getBean("userService", UserService.class);
        userService.saveUser();
    }
}

2.2 service

1)UserService

public interface UserService {
    /**
     * 模拟保存用户
     */
    void saveUser();
}

2)UserServiceImpl

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void saveUser() {
        userDao.saveUser();
    }
}

2.3 dao

1)UserDao

public interface UserDao {
    /**
     * 模拟保存用户
     */
    void saveUser();
}

2)UserDaoImpl

public class UserDaoImpl implements UserDao {
    public void saveUser() {
        System.out.printf("用户保存成功!");
    }
}

3、Spring配置文件




    

    
        
    

4、测试结果

用户保存成功!
Process finished with exit code 0

你可能感兴趣的:(spring,ioc)