Spring再接触 IOC DI

2021-07-04 11:07

阅读:592

标签:jdb   引入   path   ica   代码   net   odi   network   sys   

直接上例子

引入spring以及Junite所需要的jar包

技术分享图片

User.java

package com.bjsxt.model;

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Userservice.java

package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;



public class UserService {
    private UserDAO userDAO;  
    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
}

userDAO

package com.bjsxt.dao;
import com.bjsxt.model.User;


public interface UserDAO {
    public void save(User user);
}

userDAOimpl

package com.bjsxt.dao.impl;

import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;


public class UserDAOImpl implements UserDAO {

    public void save(User user) {
        //Hibernate
        //JDBC
        //XML
        //NetWork
        System.out.println("user saved!");
    }

}

beans.xml

"1.0" encoding="utf-8"?> 
"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-2.5.xsd"> 

  "u" class="com.bjsxt.dao.impl.UserDAOImpl">
  "userService" class="com.bjsxt.service.UserService">
      "userDAO" ref="u"/>
          
  
public class UserServiceTest {

    @Test
    public void testAdd() throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");   //读取到配置文件
        UserService service = (UserService)ctx.getBean("userService");  //Spring根据配置文件将UserDAO的实现注入到userdao 然后将userdao注入到userservice
        User u = new User();
        u.setUsername("zhangsan");
        u.setPassword("zhangsan");
        service.add(u);
    }

IOC 即invotion of control 控制反转 本来要由自己写的代码 自己确定的实现 由Spring容器帮我们实现

DI 即依赖注入 即依赖容器帮我们实例化我们实际要实例化的对象

 

Spring再接触 IOC DI

标签:jdb   引入   path   ica   代码   net   odi   network   sys   

原文地址:https://www.cnblogs.com/frankzone/p/9612971.html


评论


亲,登录后才可以留言!