您的位置:首页 > 编程语言 > Java开发

Spring_Ioc入门案例

2017-06-07 10:24 399 查看

导入jar包

4+1 : 4个核心(beans, core , context ,  expression) + 1个依赖(commons-loggins.jar)



目标类

提供UserService接口和实现类

package com.itheima.a_ioc;

public interface UserService {
public void addUser() ;
}

package com.itheima.a_ioc;

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


获得UserService实现类的实例(从Spring工厂获得,需要将实现类的全限定名称配置到xml文件)

配置文件

位置:任意, 开发中一般在classpath下(src)
名称:任意, 开发中常用 applicationContext.xml
内容: 添加Schema约束 + 配置Service
<?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 definitions here -->
<bean id = "UserServiceImplId" class = "com.itheima.a_ioc.UserServiceImpl" ></bean>

</beans>


测试

获得容器+ 获得内容

package com.itheima.a_ioc;

import org.apache.catalina.core.ApplicationContext;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIoc {
@Test
public void demo02(){
String xmlPath = "com/itheima/a_ioc/beans.xml" ;
ClassPathXmlApplicationContext a = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) a.getBean("UserServiceImplId") ;
userService.addUser();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: