标签:jar ssi classpath context 入门 encoding support oid odi
IoC控制反转,由spring统一管理类的创建,不再由自己创建。
一、导入所需jar
core、context、beans、expression、common-logging
二、目标类
package com.claudxyz.IoC; public interface UserService { public abstract void addUser(); }
package com.claudxyz.IoC; public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("ioc add user"); } }
三、配置文件
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userServiceId" class="com.claudxyz.IoC.UserServiceImpl"></bean> </beans>
id:bean的唯一标示
class:bean的地址
四、测试
package com.claudxyz.IoC; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring { public static void main(String[] args) { // 配置文件地址 String xmlPath = "com/claudxyz/IoC/applicationContext.xml"; // 固定格式 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); // 通过唯一id获取对象 UserService userService = (UserService) applicationContext.getBean("userServiceId"); // 执行代码 userService.addUser(); } // 普通调用 public void Test01(){ UserService userService = new UserServiceImpl(); userService.addUser(); } }
标签:jar ssi classpath context 入门 encoding support oid odi
原文地址:https://www.cnblogs.com/claduxyz/p/12232288.html