1、创建maven项目,修改pom.xml文件
<!--springboot项目依赖的父项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<!--注入springboot启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加junit环境的jar包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
2、dao层代码
package com.bjsxt.dao;
import org.springframework.stereotype.Repository;
/**
* Created by Administrator on 2019/2/14.
*/
@Repository
public class UserDaoImpl {
public void saveUser(){
System.out.print("insert into user...");
}
}
3、service层代码
package com.bjsxt.service;
import com.bjsxt.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Administrator on 2019/2/14.
*/
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDaoImpl;
public void saveUser(){
userDaoImpl.saveUser();
}
}
4、编写启动类
package com.bjsxt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by Administrator on 2019/2/14.
*/
@SpringBootApplication
public class App {
public static void main(String[] args){
SpringApplication.run(App.class,args);
}
}
5、编写测试文件,运行testSaveUser方法即可
package com.bjsxt.test;
/**
* Created by Administrator on 2019/2/14.
*/
import com.bjsxt.App;
import com.bjsxt.service.UserServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* SpringBoot 测试类
*
* @RunWith:启动器 SpringJUnit4ClassRunner.class:让 junit 与 spring 环境进行整合
* @SpringBootTest(classes={App.class}) 1, 当前类为 springBoot 的测试类
* @SpringBootTest(classes={App.class}) 2, 加载 SpringBoot 启动类。启动springBoot
* junit 与 spring 整合@Contextconfiguartion("classpath:applicationContext.xml")
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {App.class})
public class UserServiceTest {
@Autowired
private UserServiceImpl userServiceImpl;
@Test
public void testSaveUser(){
userServiceImpl.saveUser();
}
}
6、目录结构