1.IOC编程的介绍
IOC是控制反转的缩写,是面向对象编程中的一种设计原则,可以在一定程度上减少计算机中程序代码间的耦合度,在获得依赖对象的过程中进行反转,其中最常见的方式叫做依赖注入(简称DI),依赖注入,就是由IOC容器在程序的运行中,动态地将某种依赖关系注入到对象之中。
2.IOC编程的实现方法
IOC思想将你设计好的程序中的对象交由“容器”完成依赖查找和注入而不是将其在程序中直接控制,DI(依赖注入)是组件之间的依赖关系由程序在运行期决定,由“容器”动态的将依赖关系注入到某个组件当中,通过依赖注入我们只需要一些配置就可以实现无需代码指定目标需要的资源,不需要管资源来自于哪就完成剩下的逻辑。
3.简单的IOC编程实现案例
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<applicationcontext>
<bean id="user" class="com.icss.ioc.User"></bean>
<bean id="userDao" class="com.icss.ioc.UserDao"></bean>
<bean id="userService" class="com.icss.ioc.UserService"></bean>
<bean id="userController" class="com.icss.ioc.UserController">
<ref id="userService"></ref>
</bean>
</applicationcontext>
创建一个.xml文件用于观察和调用
ApplicationContext.java
package ioc;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ApplicationContext {
//IOC 控制反转 ==DI:依赖注入
// 定义IOC容器(Hashtable)对象
private Hashtable<String, Object> container = new <String, Object>Hashtable();
public void xmlInit(String fileName) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new FileInputStream(fileName));
// 得到节点
Node root = doc.getDocumentElement();
NodeList childList = root.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
Node childNode = childList.item(i);
NamedNodeMap nodeAttributes = childNode.getAttributes();
if (nodeAttributes != null && nodeAttributes.getLength() > 0) {
Node clazz = nodeAttributes.getNamedItem("class");
Node id = nodeAttributes.getNamedItem("id");
if (clazz != null && id != null) {
String className = clazz.getNodeValue();
String idName = id.getNodeValue();
System.out.println(className);
System.out.println(idName);
// 依据配置文件实例化类对象,存入容器
Object obj = Class.forName(className).newInstance();
container.put(idName, obj);
}
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
public Object getBean(String id) throws IllegalArgumentException, IllegalAccessException {
Object obj = this.container.get(id);
// 基于注解来实现依赖注入
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(AutoWired.class)) {
field.setAccessible(true);
// 给对象obj的属性赋值
field.set(obj, this.container.get(field.getName()));
}
}
return obj;
}
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
ApplicationContext applicationContext = new ApplicationContext();
String path = ApplicationContext.class.getResource("/").getPath();
applicationContext.xmlInit(path + "applicationContext.xml");
User user = (User) applicationContext.getBean("user");
UserControlle userController = (UserControlle) applicationContext.getBean("userController");
userController.login("zhangsan", "123456");
//实现依赖注入
}
}
具体实现部分代码
AutoWired.java
package ioc;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({ FIELD })
public @interface AutoWired {
}
UserControlle.java
package ioc;
public class UserControlle {
@AutoWired
private UserService userService;
public void login(String userName, String userPwd) {
userService.getUser();
}
}
User.java
package ioc;
public class User {
private String userName;
private String userPwd;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
UserService.java
package ioc;
public class UserService {
public User getUser() {
System.out.println("调用");
return new User();
}
}
UserDao.java
package ioc;
public class UserDao {
}