一:下载相关的包junit-4.10.jar,下载链接。
二:导入,在eclipse里面就是项目右键,Build Path->配置path ->Add external Jars.选择并导入即可。
三:创建一个UnitTestBase.java
package com.tutorialspoint;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
public class UnitTestBase {
private ClassPathXmlApplicationContext context;
private String springXmlpath;
public UnitTestBase() {}
public UnitTestBase(String springXmlpath) {
this.springXmlpath = springXmlpath;
}
@Before
public void before() {
if (StringUtils.isEmpty(springXmlpath)) {
//classpath相当于src
springXmlpath = "classpath*:spring-*.xml";
}
try {
//[,\\s]正则表达式,意思是以,和空格,tab作为分隔符,分成字符串数组
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
context.start();
} catch (BeansException e) {
e.printStackTrace();
}
}
@After
public void after() {
context.destroy();
}
@SuppressWarnings("unchecked")
protected <T extends Object> T getBean(String beanId) {
try {
return (T)context.getBean(beanId);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}
protected <T extends Object> T getBean(Class<T> clazz) {
try {
return context.getBean(clazz);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}
}
四:BeanAnnotation.java
package com.tutorialspoint;
import org.springframework.stereotype.Component;
//一个通用的bean注解
@Component
public class BeanAnnotation {
public void say(String word) {
System.out.println("BeanAnnotation : " + word);
}
}
五:TestBeanAnnotation.java
package com.tutorialspoint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
//必须要加的
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase{
public TestBeanAnnotation() {
super("classpath*:spring-injection.xml");
// TODO Auto-generated constructor stub
}
//启动的地方
@Test
public void TestSay() {
BeanAnnotation bean = super.getBean("beanAnnotation");
bean.say("Hello Junit");
}
}
xml:spring-injection.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint"></context:component-scan>
<!-- <bean id="beanAnnotation" class="com.tutorialspoint.BeanAnnotation"></bean>-->
</beans>
注意:这里并没有在xml里面配置BeanAnnotation的 bean,用到了组件自动扫描的功能,自动生成beanAnnotation可以扫描
当然如果你想指定他的名称,只需要@Component("Name")
Component组件 Controller控制层 Service业务层 Repository数据层
还有导入jar包的时候不要重复也不要少!!