您的位置:首页 > 编程语言 > Java开发

spring框架ioc控制反转的简单实现

2020-03-29 13:00 375 查看

如何理解spring中的控制反转

就用一个案例来感受一下

在经典的ssm架构中 service层中业务层serviceimpl实现接口 并调用dao层接口。

//dao层
public interface IAccountDao {

/**
*保存账户
*/
void saveAccount();
}
//没用mybtais获取数据,直接自己实现dao层接口
public class AccountDaoImpl implements IAccountDao {

@Override
public void saveAccount() {
System.out.println("保存了账户");
}
}
//service层接口
public interface IAccountService {

/**
* 模拟保存
*/
void saveAccount();
}
/**
* @author DELL
* 业务层实现类
*/
public class AccountServiceImpl implements IAccountService {

//    private IAccountDao accountDao = new AccountDaoImpl();

private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");

@Override
public void saveAccount() {
accountDao.saveAccount();
}
}

模拟controller

public class Client {
public static void main(String[] args) {
//        IAccountService ac = new AccountServiceImpl();
IAccountService ac = (IAccountService) BeanFactory.getBean("accountService");
ac.saveAccount();
}
}

通过以上代码可知两次需要获取实例对象,为了解耦体现ioc控制反转的效果

/**
* 一个创建bean对象的工厂
* javabean =/= 实体类
* 它就是创建我们service和dao对象的
* 第一个 需要一个配置文件 来配置我们的servece和dao
* 通过读取配置文件中的配置内容,反射创建对象
* @author DELL
*/
public class BeanFactory {
/**
* 定义一个Properties
*/
private static Properties props;

/**
* 定义一个Map,用于存放我们要创建的对象.我们把它称之为容器
*/
private static Map<String,Object> beans;

//使用静态代码块为Properties对象赋值
static {
try {
props = new Properties();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
System.out.println(in+"工厂方法获得的数据");
props.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration<Object> keys = props.keys();
//遍历枚举
while(keys.hasMoreElements()){
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器之中
beans.put(key,value);
}

} catch (Exception e ) {
throw new ExceptionInInitializerError("初始化properties失败");
}
}

/**
* 根据Bean的名称获取bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}

其中在方法中new properts和BeanFactory.class.getClassLoader().getResourceAsStream(“bean.properties”);可以查看大佬博客来理解

ps:properts读取配置文件的
转载别人理解properts的

如何理解BeanFactory.class.getClassLoader().getResourceAsStream
就是获得路径的

  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_44801336 发布了54 篇原创文章 · 获赞 5 · 访问量 749 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: