创建项目自动会导入Junit模块
@SpringBootTest
class JuintApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
userDao.login();
}
}
Q:如果将测试类换一个包,无法测试?
原因:测试需要使用到spring容器中自动装配的对象,如果测试类在启动类的包及其子包,则找的到(默认扫描启动类的包及其子包),否则无效。
解决方法:显式指向启动类@SpringBootTest(classes = JuintApplication.class)
@SpringBootTest(classes = JuintApplication.class)
class JuintApplicationTests {
等效于
@SpringBootTest
@ContextConfiguration(classes = JuintApplication.class)
class JuintApplicationTests {
手动导入或者创建项目时候勾选
<!--MyBatis 整合 SpringBoot 的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--MySQL 的驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
# 应用名称
spring.application.name=springBoot006_mybatis
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
##下面这些内容是为了让MyBatis映射
##指定Mybatis的Mapper文件
#mybatis.mapper-locations=classpath:mappers/*xml
##指定Mybatis的实体目录
#mybatis.type-aliases-package=com.zjh.springboot006_mybatis.mybatis.entity
@Mapper
public interface UserDao {
@Select("select * from user")
List<User> getAll();
}
@SpringBootTest
class SpringBoot006MybatisApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
System.out.println(userDao.getAll());
}
}
此处为语雀内容卡片,点击链接查看:https://www.yuque.com/u12232008/xpazgo/gel6fb
//@MapperScan("com.zjh.springboot.mapper")
@MapperScan(basePackages = "com.zjh.springboot.mapper")
在pom.xml中的标签进行配置resource允许java包编译.xml文件
默认情况下,Mybatis 的 xml 映射文件不会编译到 target 的 class 目录下,所以我们需要在 pom.xml 文件中配置 resource 对xml文件放行
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
resources>
必须进行映射文件的路径配置
# 指定 Mybatis 映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml
在service层要使用事务的方法上加@Transactional
DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry location="D:\mysql-connector-java-8.0.23.jar"/>
<context id="tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/xiaomissm"
userId="root"
password="123456">
jdbcConnection>
<javaModelGenerator targetPackage="com.zjh.springboot.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
javaModelGenerator>
<sqlMapGenerator targetPackage="com.zjh.springboot.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.zjh.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
javaClientGenerator>
<table tableName="t_student" domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
context>
generatorConfiguration>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.6version>
<configuration>
<configurationFile>GeneratorMapper.xmlconfigurationFile>
<verbose>trueverbose>
<overwrite>trueoverwrite>
configuration>
plugin>
生成成功
如果出现生成的pojo类不符合预期,在GeneratorMapper.xml
的
中加入
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/classroom"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
此处为语雀内容卡片,点击链接查看:https://www.yuque.com/u12232008/nddmz0/vwrylx
方法一
由于SpringBoot中未收录MyBatis-Plus的坐标版本,需要指定对应的Version
初始只添加mysql坐标,然后到maven仓库查找MP坐标手动加入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
方法二
直接使用aliyun的配置
这一步和mybatis一样
# 应用名称
spring.application.name=springBoot006_mybatis
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
##下面这些内容是为了让MyBatis映射
##指定Mybatis的Mapper文件
#mybatis.mapper-locations=classpath:mappers/*xml
##指定Mybatis的实体目录
#mybatis.type-aliases-package=com.zjh.springboot006_mybatis.mybatis.entity
@Mapper
public interface UserDao extends BaseMapper<User> {
}
@SpringBootTest
class SpringBoot007MpApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
System.out.println(userDao.selectById(1));
}
}
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
两种方式
方式一
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 应用名称
spring.application.name=springBoot006_mybatis
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
#数据库类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
##指定Mybatis的实体目录
#mybatis.type-aliases-package=com.zjh.springboot006_mybatis.mybatis.entity
方式二
官方推荐使用thymeleaf模板
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
dependency>
SpringBoot 要求 jsp 文件必须编译到指定的 META-INF/resources 目录下才能访问,否则 访问不到。
在pom.xml中的build标签配置
<resources>
<resource>
<directory>src/main/webappdirectory>
<targetPath>META-INF/resourcestargetPath>
<includes>
<include>**/*.*include>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.*include>
includes>
resource>
resources>
注意:不加下面这段
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.*include>
includes>
resource>
打包会没有application.properties文件,因为上面指定webapp为resource,会覆盖springBoot默认resources是默认资源文件夹的规则
#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg","helloSpringBoot");
modelAndView.setViewName("hello");
return modelAndView;
}
@Controller
public class SpringBootController {
@RequestMapping(value = "/springBoot/jsp")
public String jsp(Model model) {
model.addAttribute("data","SpringBoot 前端使用 JSP 页面!");
return "index";
}
直接在 main 方法中,根据 SpringApplication.run()方 法获取返回的 Spring 容器对象,再获取业务 bean 进行调用
创建一个 SpringBoot Module
注意:什么都不要勾选
没有webapp文件夹,类似于maven空项目
测试
编写接口和实现类UserServiceImpl
public interface UserService {
String sayHello(String message);
}
@Service
public class UserServiceImpl implements UserService {
@Override
public String sayHello(String message) {
return "Hello,SpringBoot Java!";
}
使用@Service把UserServiceImpl注入
在Application 类的main方法中调用UserServiceImpl
@SpringBootApplication
public class Application {
public static void main(String[] args) {
/**
* SpringBoot 程序启动后,返回值是 ConfigurableApplicationContext,它也是一个
Spring 容器对象
* 它其它相当于原来 Spring 中启动容器 ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("");
*/
//获取 SpringBoot 程序启动后的 Spring 容器
ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args);
//从 Spring 容器中获取指定 bean 的对象
UserService userService = (UserService)
context.getBean("userServiceImpl");
//调用业务 bean 的方法
String sayHello = userService.sayHello();
System.out.println(sayHello);
}
}
SpringBoot 程序启动后,返回值是ConfigurableApplicationContext
,它也是一个Spring 容器对象相当于原来 Spring 中启动容器ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("");
这个方法是从容器中取出userServiceImpl的bean对象进行使用
Spring boot 的入口类实现 CommandLineRunner 接口
@SpringBootApplication
public class Application2 implements CommandLineRunner {
//第二步:通过容器获取 bean,并注入给 userService
@Autowired
private UserService userService;
public static void main(String[] args) {
//第一步:SpringBoot 的启动程序,会初始化 spring 容器
SpringApplication.run(Application2.class,args);
}
//覆盖接口中的 run 方法
@Override
public void run(String... args) throws Exception {
//第三步:容器启动后调用 run 方法,在该方法中调用业务方法
String sayHello = userService.sayHello();
System.out.println(sayHello);
}
}
@WebServlet(urlPatterns = "/myServlet")
相当于之前在web.xml中进行 的配置
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.getWriter().print("My SpringBoot Servlet");
response.getWriter().flush();
response.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request,response);
}
@SpringBootApplication
@ServletComponentScan(basePackages = "com.abc.springboot.servlet")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.getWriter().print("My SpringBoot Servlet");
response.getWriter().flush();
response.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request,response);
}
@Configuration //将此类作为配置类
public class ServletConfig {
//@Bean 是一个方法级别上的注解,主要用在配置类里
/*
* 相当于一个
*
*
* */
@Bean
public ServletRegistrationBean myServletRegistrationBean() {
//将自定义 servlet 注册到注册 Servlet 类中,并指定访问路径
ServletRegistrationBean servletRegistrationBean = new
ServletRegistrationBean(new MyServlet(), "/springboot/myServlet");
return servletRegistrationBean;
}
}
不需要扫描servelt包
和使用servlet基本一致,也是两种配置方法
@WebFilter( urlPatterns = "/user/*" )
public class MyFilter implements Filter {
@Override
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain ) throws IOException, ServletException
{
System.out.println( "-------------您已进入过滤器---------------" );
filterChain.doFilter( servletRequest, servletResponse );
}
}
在 主 应 用 程 序 Application 类上添加 @ServletComponentScan("basePackages = “com.abc.springboot.filter”)
@ServletComponentScan( basePackages = "com.abc.springboot.filter" )
@SpringBootApplication
public class Application {
public static void main( String[] args )
{
SpringApplication.run( Application.class, args );
}
}
}
MyFilter不需要加注解
@Configuration /* 定义为配置类 */
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistration()
{
/* 注册过滤器 */
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean( new MyFilter() );
/* 添加过滤路径 */
filterRegistrationBean.addUrlPatterns( "/user/*" );
return filterRegistrationBean;
}
}
@WebServlet("/servlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws
ServletException, IOException
{
resp.getWriter().print( "Hello World,世界您好!" );
/* 设置浏览器编码格式 */
resp.setContentType( "text/html;character=utf-8" );
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
doGet( req, resp );
}
}
启动类加包扫描注解
@ServletComponentScan("com.zjh.springboot.servlet")
输出乱码
@Configuration /* 设置为配置类 */
public class SystemConfig {
@Bean
public ServletRegistrationBean myServletRegistration() {
ServletRegistrationBean servletRegistrationBean =
new ServletRegistrationBean(new MyServlet(),
"/springboot/myServlet");
return (servletRegistrationBean);
}
@Bean
public FilterRegistrationBean characterFilterRegistration() {
/*
* 设置字符编码过滤器
* CharacterEncoding 是由 Spring 提供的一个字符编码过滤器,之前是配置在
*web.xml 文件 中
* */
CharacterEncodingFilter characterEncodingFilter = new
CharacterEncodingFilter();
/* 强制使用指定字符编码 */
characterEncodingFilter.setForceEncoding(true);
/* 设置指定字符编码 */
characterEncodingFilter.setEncoding("UTF-8");
/* 创建过滤器注册 bean */
FilterRegistrationBean filterRegistrationBean = new
FilterRegistrationBean();
/* 设置字符编码过滤器 */
filterRegistrationBean.setFilter(characterEncodingFilter);
/* 设置字符编码过滤器路径 */
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
对比传统springmvc的字符编码设置
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
#关闭 springboot 的 http 字符编码支持
#只有关闭该选项后,spring 字符编码过滤器才生效
server.servlet.encoding.enabled=false
编写完servlet后不需要写配置类
直接在application.properties 中配置字符编码
#设置请求响应的字符编码
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8
测试成功