赞
踩
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> </parent> <groupId>com.xsl</groupId> <artifactId>springboot_hello</artifactId> <version>1.0-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
类名上添加@SpringBootApplication注解,表示工程引导类,为工程的入口,编写一个main方法,启动类SpringApplication调用run方法调用。项目已经可以为一个web项目启动了
package com.xsl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* springboot工程都有一个工程引导类,工程入口类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
package com.xsl.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; @RestController public class HelloController { @GetMapping("/hello") public String hello(){ System.out.println(dataSource); return "hello springboot!"; } }
这样一个springboot最简单的案例就完成了,用浏览器访问即可得到一个返回的hello springboot!
这里以读取配置文件,初始化DataSource加入容器为例
因为要初始化一个连接池,所以导入druid连接池的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
创建一个properties文件,这里我取名jdbc.properties,将连接池的信息写入配置文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc.msql://localhost:3306/springboot_start
jdbc.username=root
jdbc.password=root
创建一个类,用于读取配置文件,并且将DataSource添加到spring容器中
package com.xsl.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; /** * @Configuration:声明一个配置类,代替xml文件 * @PropertySource("classpath:jdbc.properties"):指定外部属性文件 * @Bean:加入Bean容器,若配置在方法上,则将方法的返回值加入容器 * @Value:将从配置文件读出的数据注入到对象中 */ @Configuration @PropertySource("classpath:jdbc.properties") public class JdbcConfig { @Value("${jdbc.url}") private String url; @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } }
在Controller中注入注入一个DataSource,debug查看dataSource中是否又我们配置文件的值
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@GetMapping("/hello")
public String hello(){
System.out.println(dataSource);
return "hello springboot!";
}
}
springboot会自动加载以application为名的文件。
package com.xsl.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @ConfigurationProperties:从application配置文件中读取配置项 * prefix:配置文件的前缀 * 配置项中的变量名必须要用与前缀之后的配置项名称保持松散绑定(相同) */ @ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String url; private String driverClassName; private String username; private String password; public JdbcProperties() { } @Override public String toString() { return "JdbcProperties{" + "url='" + url + '\'' + ", driverClassName='" + driverClassName + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public JdbcProperties(String url, String driverClassName, String username, String password) { this.url = url; this.driverClassName = driverClassName; this.username = username; this.password = password; } }
【注意】@EnableConfigurationProperties注解如果报错,添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<!--不传递依赖-->
<optional>true</optional>
</dependency>
package com.xsl.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; /** * @Configuration:声明一个配置类,代替xml文件 * @PropertySource("classpath:jdbc.properties"):指定外部属性文件 * @Bean:加入Bean容器,若配置在方法上,则将方法的返回值加入容器 * @Value:将从配置文件读出的数据注入到对象中 * @EnableConfigurationProperties:使用配置类可以将DataSource注入到spring中 */ @Configuration //@PropertySource("classpath:application.properties") @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfig { // @Value("${jdbc.url}") // private String url; // @Value("${jdbc.driverClassName}") // private String driverClassName; // @Value("${jdbc.username}") // private String username; // @Value("${jdbc.password}") // private String password; // // @Bean // public DataSource dataSource(){ // DruidDataSource druidDataSource = new DruidDataSource(); // druidDataSource.setDriverClassName(driverClassName); // druidDataSource.setUrl(url); // druidDataSource.setUsername(username); // druidDataSource.setPassword(password); // return druidDataSource; // } @Bean public DataSource dataSource(JdbcProperties jdbcProperties){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(jdbcProperties.getDriverClassName()); druidDataSource.setUrl(jdbcProperties.getUrl()); druidDataSource.setUsername(jdbcProperties.getUsername()); druidDataSource.setPassword(jdbcProperties.getPassword()); return druidDataSource; } }
这里要注意的是,yml与properties文件除了展示形式不一样以外,使用都是一致的。
(1)、树状层级结构展示配置项
(2)、次级换行空两格
(3)、键值对格式
值为一个
键:(空格)值
值为集合
键:
(空格)-(空格)值
(空格)-(空格)值
(4)、支持多文件配置,但是yml文件的配置名必须为 application-***.yml,且这些文件需要在application.yml文件中激活后才能使用,properties与yml文件同时存在,且能同时读取,若键名相同,则properties文件的优先级高
xsl:
name: 我本人
#连接池
jdbc:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql//localhost:3306/springboot_start
username: root
password: root
#激活配置文件application-xsl.yml
spring:
profiles:
active: xsl
@RestController public class HelloController { @Autowired private DataSource dataSource; @Value("${xsl.name}") private String name; @GetMapping("/hello") public String hello(){ System.out.println(dataSource); System.out.println(name); return "hello springboot!"; } }
内部使用Slfj记录日志信息
package com.xsl.interceptor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j public class MyInterceptor implements HandlerInterceptor { /** * 前置拦截器 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.debug("this is preHandle"); return true; } /** *后置拦截器 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.debug("this is postHandle"); } /** * 完成时拦截器 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.debug("this is afterCompletion"); } }
#设置日志信息记录级别
logging:
level:
com.xsl.interceptor.MyInterceptor: debug
org.springframework: info
package com.xsl.config; import com.xsl.interceptor.MyInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** *创建一个配置类。实现WebMvcConfigurer接口 */ @Configuration public class MvcConfig implements WebMvcConfigurer { @Bean public MyInterceptor myInterceptor(){ //将拦截器交给spring容器管理 return new MyInterceptor(); } /* *重写addInterceptors方法 */ @Override public void addInterceptors(InterceptorRegistry registry) { //拦截所有 registry.addInterceptor(myInterceptor()).addPathPatterns("/*"); } }
<!--jdbc依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
hikar连接池为默认连接池,所以不用额外导入依赖
#激活配置文件
spring:
profiles:
active: xsl
#以下部分为hikar连接池配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_start
username: root
password: root
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
mybatis:
type-aliases-package: com.xsl.entity
mapper-locations: classpath:mappers/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
package com.xsl.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 可以在Mapper接口配置Mapper注解,但是需要每个接口都添加可以在启动类添加MapperScan注解扫描所有的包
*/
//@Mapper
public interface UserMapper {
}
启动器开启mybatis包扫描
@SpringBootApplication
@MapperScan("com.xsl.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
package com.xsl.mapper;
import com.xsl.entity.User;
import tk.mybatis.mapper.common.Mapper;
/**
* 可以在Mapper接口配置Mapper注解,但是需要每个接口都添加可以在启动类添加MapperScan注解扫描所有的包
*/
//@Mapper
public interface UserMapper extends Mapper<User> {
}
package com.xsl; //注意这两个的区别 //import org.mybatis.spring.annotation.MapperScan; import tk.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * springboot工程都有一个工程引导类,工程入口类 */ @SpringBootApplication //@MapperScan("com.xsl.mapper") @MapperScan("com.xsl.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
import lombok.Data; import tk.mybatis.mapper.annotation.KeySql; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Data @Table(name = "tb_user") public class User { @Id //主键回填 @KeySql(useGeneratedKeys = true) @Column(name = "id") private Long id; }
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
package com.xsl.service; import com.xsl.entity.User; 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.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @Test public void selectAll() { List<User> userList = userService.selectAll(); System.out.println(userList); } @Test @Transactional public void saveUser() { } }
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。