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

Spring之Hello

2016-04-21 23:11 561 查看

下载spring包

Download

一, 添加所需jar包

commons-logging-1.3.jar

spring-beans-4.2.5.RELEASE.jar

spring-context-4.2.5.RELEASE.jar

spring-context-support-4.2.5.RELEASE.jar

spring-core-4.2.5.RELEASE.jar

spring-expression-4.2.5.RELEASE.jar

spring-test-4.2.5.RELEASE.jar

二, 编写接口

package com.lee.service;

public interface Hello {
public void say(String name);   //方法说明
}


三, 编写接口实现类

package com.lee.service.impl;

import org.springframework.stereotype.Service;
import com.lee.service.Hello;

@Service    //注册bean
public class HelloImpl implements Hello {
@Override
public void say(String name) {
System.out.println("Hello " + name);
}
}


四, 编写applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<!-- 使用了注解, 需要告诉spring上下文去哪里找, 并注册到spring上下文中 -->
<context:component-scan base-package="com.lee" />
<!--
若不使用注解, 则需要添加以下代码注册bean到spring上下文中
<bean id="hello" class="com.lee.service.impl.HelloImpl" />
-->
</beans>


五, 使用JUnit4测试框架测试spring

package com.lee.test.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.lee.service.Hello;

@RunWith(SpringJUnit4ClassRunner.class)    //整合spring和JUnit4
@ContextConfiguration(locations="classpath:applicationContext.xml")//声明xml所在
public class HelloTest {

@Autowired   //自动装载
private Hello hello;

@Test
public void hello() {
hello.say("Lee");
}
}


文件格式



控制台输出

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