前言

今天来说点Spring IOC 的应用,还有简单实现的原理。

正文

简单粗暴一点吧!先来个类图看看各个类之间的关系。

Spring IOC的实现demo_spring

通过这个类图可以看到各个类之间的关系,接下来就把各个类的代码贴出来

package com.hao.server;

public interface UserServer {
void getUser();
}
package com.hao.server;

import com.hao.dao.UserDao;
import com.hao.dao.UserDaoImpl;

public class UserServerImpl implements UserServer {

private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
@Override
public void getUser(){
userDao.getUser();
}
}
package com.hao.dao;

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


public class UserDaoImpl implements UserDao {
@Override
public void getUser(){
System.out.println("使用默认数据库");
}
}
package com.hao.dao;


public class UserMysqlDaoImpl implements UserDao {
@Override
public void getUser(){
System.out.println("使用mysql数据库");
}
}
package com.hao.dao;

import java.sql.SQLOutput;


public class UserServersqlDaoImpl implements UserDao {
@Override
public void getUser(){
System.out.println("使用server数据库");
}
}

下面的MyTest重复展示了从传统的实例化对象到通过IOC机制来实例化对象的过程。注释的代码也要看啊!

import com.hao.dao.UserDaoImpl;
import com.hao.dao.UserMysqlDaoImpl;
import com.hao.dao.UserServersqlDaoImpl;
import com.hao.server.UserServer;
import com.hao.server.UserServerImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MyTest {
public static void main(String[] args) {
//UserServer userServer=new UserServerImpl();
//((UserServerImpl) userServer).setUserDao(new UserServersqlDaoImpl());
//((UserServerImpl) userServer).setUserDao(new UserDaoImpl());
//((UserServerImpl) userServer).setUserDao(new UserMysqlDaoImpl());
//userServer.getUser();
//获取ApplicationContext :拿到spring的容器
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
UserServerImpl userServer=(UserServerImpl) context.getBean("UserServiceImpl");
userServer.getUser();

//UserMysqlDaoImpl userMysql=(UserMysqlDaoImpl) context.getBean("mysqlImpl");
//userMysql.getUser();


}
}

好像还少一个bean.xml文件

<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="mysqlImpl" class="com.hao.dao.UserMysqlDaoImpl">
<!-- collaborators and configuration for this bean go here -->
</bean>

<bean id="serversImpl" class="com.hao.dao.UserServersqlDaoImpl">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="UserServiceImpl" class="com.hao.server.UserServerImpl">
<!--<property name="userDao" ref="serversImpl"></property>-->
<property name="userDao" ref="mysqlImpl"></property>
</bean>

</beans>

整个代码就全了,运行调试一下可能会对整个代码的运行过程更清楚。

结束

写完感觉这个有点水啊,全是代码没有说什么话,反正整个机制都在代码中体现出来了。最后贴一张表大家体会一下吧!

Spring IOC的实现demo_spring_02