1. 程式人生 > 其它 >Spring使用set動態注入實現IOC原型

Spring使用set動態注入實現IOC原型

技術標籤:JavaIOC

package com.chenxb.dao;

public interface UserDao {
    void getUser();
}
package com.chenxb.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public void getUser() {
        System.out.println("獲取User");
    }
}
package com.chenxb.dao;

public class
UserDaoMysqlImpl implements UserDao { @Override public void getUser() { System.out.println("Mysql 獲取User"); } }
package com.chenxb.dao;

public class UserDaoOracleImpl implements UserDao {

    @Override
    public void getUser() {
        System.out.println("Oracle 獲取User"
); } }
package com.chenxb.pojo;

import lombok.Data;

@Data
public class User {
    int id;
    String name;
    String password;
}
package com.chenxb.service;

public interface UserService {
    void getUser();
}
package com.chenxb.service;

import com.chenxb.dao.UserDao;
import com.chenxb.dao.
UserDaoImpl; import com.chenxb.dao.UserDaoMysqlImpl; import com.chenxb.dao.UserDaoOracleImpl; public class UserServiceImpl implements UserService { /** * 第一種做法 * 普通的三層切換多個dao,只能去修改service中的new物件 */ // private UserDao userDao = new UserDaoImpl(); // private UserDao userDao = new UserDaoMysqlImpl(); // private UserDao userDao = new UserDaoOracleImpl(); /** * 第二種寫法 * 利用set進行動態注入 */ private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void getUser() { userDao.getUser(); } }
import com.chenxb.dao.UserDaoOracleImpl;
import com.chenxb.pojo.User;
import com.chenxb.service.UserService;
import com.chenxb.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        /**
         * 第一種做法
         * 普通的三層切換多個dao,只能去修改service中的new物件
         */
//        UserService userService = new UserServiceImpl();
//        userService.getUser();

        /**
         * 第二種寫法
         * 利用set進行動態注入
         */
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl)userService).setUserDao(new UserDaoOracleImpl());
        userService.getUser();


//        //獲取spring上下文物件
//        ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
//        //物件都在spring上下文物件裡,要用就直接去拿就行了
//        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
//        userServiceImpl.getUser();
    }
}

在這裡插入圖片描述