简单的Spring IoC入门学习

一、导入所需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();
    }
}

 

上一篇:【Spring】AOP(二)自定义来实现AOP


下一篇:Spring代理模式及AOP