一、开发环境
eclipse版本:4.4.2
maven版本:3.5.0
junit版本:4.12
spring版本:5.0.9.RELEASE
JDK版本:1.8.0_102
二、项目结构
三、项目实现
1、新建项目
Maven包配置依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> |
---|
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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- 扫描所有类型的bean --> <context:component-scan base-package="com.spring.lsh.*"/> </beans> |
---|
2、创建测试类
@RunWith注解,使用junit整合spring
@ContextConfiguration注解,指定spring容器的位置
@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations={"classpath*:applicationContext.xml"}) @ContextConfiguration(locations={"file:D:* /webapp/WEB-INF/applicationContext.xml"}) |
---|
publicclass UserServiceImpl_spring_test { @Autowired private UserService userService; @Test publicvoid testFindByID() { User user=userService.findByID(1); System.out.print(user.getName()); } |
---|
@Service("userService") publicclass UserServiceImpl implements UserService{ public User findByID(Integer id){ if(id==1){ User user=new User(); user.setAge("7"); user.setName("放假"); returnuser; } if(id==2){ User user=new User(); user.setAge("70"); user.setName("国庆"); returnuser; } returnnull; } |
---|
4、Use.java& UserService.java类
publicclass User { private Integer id; private String name; private String age; public Integer getId() { returnid; } publicvoid setId(Integer id) { this.id = id; } public String getName() { returnname; } publicvoid setName(String name) { this.name = name; } public String getAge() { returnage; } publicvoid setAge(String age) { this.age = age; } |
---|
@Component publicinterface UserService { public User findByID(Integer id); } |
---|
publicstaticvoid main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"file:D:/software/dubbo/Spring_maven_demo1/src/main/webapp/WEB-INF/applicationContext.xml"}); UserService us = (UserService)context.getBean("userService"); User user=us.findByID(1); System.out.print(user.getName()); } |
---|
6、运行