Spring入门案例(Ioc 控制反转)

xiaoxiao2025-10-19  7

1、首先导入spring必须要的4个核心包(beans、core、context、expression)+1个依赖(commons-logging...jar)

            

2、目标类

  提供UserService接口和实现类

package ioc; public interface UserService { public void addUser(); }

 

public class UserServiceImpl implements UserService { @Test public void addUser() { System.out.println("ioc add user"); } }

  之前写代码直接new一个实例,现在学习了spring之后,将由spring创建对象实例-->Ioc控制反转(Inverse of Control)

  之后需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中

3、配置文件

  位置一般放在classpath下(src),名字约定俗成的:applicationContext.xml。添加schema约束

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "> <!-- 将user对象交给spring容器管理 <bean> 配置需要创建的对象 id:用于之后从spring容器获得实例时使用 class:需要创建的全限定类名 --> <bean name="user" class="ioc.UserServiceImpl"></bean> </beans>

 位置如图:

4、测试

 

 

 

 

 

 

 

 

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-5038199.html

最新回复(0)