spring的IoC环境搭建

来源:互联网 发布:mac phpmyadmin 配置 编辑:程序博客网 时间:2024/05/22 15:57

1.拷贝jar包(4个核心加一个依赖)

spring-framework-3.0.2.RELEASE-dependencies

spring-framework-3.2.0.RELEASE-dist


2.编写目标类IoC实现

(1)提供接口和实现类

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

(2)获得实现类的实例

3配置文件

位置任意,名称任意(src)

<?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"><!-- 配置service <bean> 配置需要创建的对象id :用于之后从spring容器获得实例时使用的class :需要创建实例的全限定类名--><bean id="userServiceId" class="com.yang01.ioc.UserServiceImpl"></bean></beans>
4测试类

package com.yang01.ioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestIoC {@Testpublic void demo01(){//之前开发UserService userService = new UserServiceImpl();userService.addUser();}@Testpublic void demo02(){//从spring容器获得//1 获得容器String xmlPath = "com/yang01/ioc/beans.xml";ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);//2获得内容 --不需要自己new,都是从spring容器获得UserService userService = (UserService) applicationContext.getBean("userServiceId");userService.addUser();}}
十月 05, 2016 11:40:15 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@17392df: startup date [Wed Oct 05 11:40:15 CST 2016]; root of context hierarchy十月 05, 2016 11:40:15 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [com/yang01/ioc/beans.xml]十月 05, 2016 11:40:15 上午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1a43bd4: defining beans [userServiceId]; root of factory hierarchya_ico add user



0 0