一 项目搭建
新建maven项目–>导入web开发的starter依赖–>搭建项目结构–>全局配置文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
</dependencies>
@SpringBootApplication
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class, args);
}
}
启动类一般放在最外侧,这样项目启动时@SpringBootApplication注解会扫描该类以及其子包下的所有类。
@Controller
@RequestMapping(value = "/test")
public class HelloController {
@RequestMapping(value = "/hello")
@ResponseBody
public Result sayHello(HttpServletRequest request) {
Result result=new Result();
result.setData("hello world!");
result.setReturnCode("00000");
result.setReturnMsg("success");
return result;
}
}
application.properties中配置访问路径和端口
server.port=8080
server.servlet.context-path=/boot
postman上发请求测试
二 原理初探
2.1 @SpringBootApplication 注解解析
@SpringBootApplication注解主要组合了@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解。
@Configuration:这个注解的作用就是声明当前类是一个配置类,然后Spring会自动扫描到添加了@Configuration的类,读取其中的配置信息,而@SpringBootConfiguration是来声明当前类是SpringBoot应用的配置类,项目中只能有一个。所以一般我们无需自己添加。
@EnableAutoConfiguration:开启自动配置,告诉SpringBoot基于所添加的依赖,去“猜测”你想要如何配置Spring。比如我们引入了spring-boot-starter-web,而这个启动器中帮我们添加了tomcat、SpringMVC的依赖,此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!我们使用SpringBoot构建一个项目,只需要引入所需框架的依赖,配置就可以交给SpringBoot处理了
@ComponentScan:配置组件扫描的指令,提供了类似与context:component-scan标签的作用,通过basePackageClasses或者basePackages属性来指定要扫描的包。
如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包,而我们的@SpringBootApplication注解声明的类就是main函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较前的包目录中。
三。配置
3.1 数据源配置
appication.properties
#数据源配置,注意驱动的版本,url会有不同的写法
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.Driver-class-name=com.mysql.cj.jdbc.Driver
#常用的数据源配置
spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database.
spring.datasource.data= # Data (DML) script resource references.
spring.datasource.data-username= # Username of the database to execute DML scripts (if different).
spring.datasource.data-password= # Password of the database to execute DML scripts (if different).
spring.datasource.dbcp2.*= # Commons DBCP2 specific settings
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.generate-unique-name=false # Whether to generate a random datasource name.
spring.datasource.hikari.*= # Hikari specific settings
spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.
spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool).
spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set.
spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password= # Login password of the database.
spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql).
spring.datasource.schema= # Schema (DDL) script resource references.
spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different).
spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different).
spring.datasource.separator=; # Statement separator in SQL initialization scripts.
spring.datasource.sql-script-encoding= # SQL scripts encoding.
spring.datasource.tomcat.*= # Tomcat datasource specific settings
spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name.
spring.datasource.xa.properties= # Properties to pass to the XA data source.
获取系统默认使用的数据源类型
```java
@Component
public class ShowUtil implements ApplicationContextAware {
private ApplicationContext context=null;
private Logger log=LoggerFactory.getLogger(ShowUtil.class);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context=applicationContext;
DataSource ds=context.getBean(DataSource.class);
log.info("当前使用的数据源类型:"+ds.getClass());
}
}
INFO 17124 --- [main] com.ljx.boot.server.ShowUtil : 当前使用的数据源类型:class com.zaxxer.hikari.HikariDataSource
**SpringBoot支持的数据源类型:**
1.com.zaxxer.hikari.HikariDataSource(SpringBoot2.0以上默认使用此数据源,号称JavaWEB当前速度最快的数据源,相比于传统的C3P0、DBCP、Tomcatjdbc等连接池更加优秀)
2.org.apache.tomcat.jdbc.pool.DataSource
3.org.apache.commons.dbcp2.BasicDataSource
也可以通过设置使用第三方的数据源
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
INFO 17504 --- [main] com.ljx.boot.server.ShowUtil : 当前使用的数据源类型:class org.apache.commons.dbcp2.BasicDataSource
3.1.1 有了数据源DataSource后就可以获取数据库连接Connection,从而可以使用原生的JDBC来控制数据库。
@Controller
@RequestMapping(value = "/dataSource")
public class DataSourceController {
@Autowired
private DataSource ds;
@RequestMapping(value = "/origin")
@ResponseBody
public Result origin(HttpServletRequest request) {
Result result=new Result();
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn=ds.getConnection();
ps=conn.prepareStatement("select * from user");
rs=ps.executeQuery();
List list=new ArrayList();
while(rs.next()) {
User temp=new User();
temp.setUage(rs.getInt("uage"));
temp.setUid(rs.getInt("uid"));
temp.setUname(rs.getString("uname"));
list.add(temp);
}
result.setData(list);
}catch (Exception e) {
// TODO: handle exception
}finally {
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
result.setReturnCode("00000");
result.setReturnMsg("success");
return result;
}
}
3.1.2 spring本身也对JDBC做了轻量级的封装,就是org.springframework.jdbc.core.JdbcTemplate。
springboot不仅提供了默认的数据源,还将配置好的JdbcTemplate放入了容器,所以只需做注入就可以直接使用JdbcTemplate对数据库进行操作。
@Controller
@RequestMapping(value = "/dataSource")
public class DataSourceController {
@Autowired
private JdbcTemplate template;
@RequestMapping(value = "/template")
@ResponseBody
public Result template(HttpServletRequest request) {
Result result=new Result();
List list=template.queryForList("select * from user");
result.setData(list);
result.setReturnCode("00000");
result.setReturnMsg("success");
return result;
}
}
3.1.3 使用第三方数据库操作框架(MyBatis Hibernate)
使用MyBatis操作数据库的基本步骤
Controller接收请求,调用注入的service对象进行处理,提供service的实现类serviceImp作为bean放入spring容器。serviceImpl中注入dao的bean,进行数据库操作,dao使用mapper.xml通过代理实例化dao对象。
1.controller层,注入service,接收request请求,设置返回的视图
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryAll")
@ResponseBody
public Result getAllUsers(HttpServletRequest request) {
Map map=new HashMap();
List<User> list=userService.queryAll(map);
Result result=new Result();
result.setData(list);
result.setStatus("000000", "success");
return result;
}
}
2.service层,定义接口方法
public interface UserService {
public List<User> queryAll(Map param);
public int insert(Map param);
}
3.serviceImpl,设置注解支持自动扫描,注入dao对象,书写业务代码
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao dao;
public List<User> queryAll(Map param) {
return dao.queryAll(param);
}
public int insert(Map param) {
return dao.insert(param);
}
}
4.dao层,定义直接操作数据库的方法,设置注解支持自动扫描
@Repository
public interface UserDao {
public List<User> queryAll(Map param);
public int insert(Map param);
}
5.编写mapper.xml文件,供动态代理实现dao的bean
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljx.boot.server.dao.UserDao">
<select id="queryAll" parameterType="Map" resultType="com.ljx.boot.server.entity.User">
select * from user
<where>
<if test="uname!=null and nuanme!=''"> and uname=${uname}</if>
</where>
</select>
<insert id="insert" useGeneratedKeys="true" keyColumn="uid">
insert into user(uid,uname,upassword,uage)
values(default,${uname},${upassword},${uage})
</insert>
</mapper>
6.配置
启动器配置dao的自动扫描路径
@SpringBootApplication
@MapperScan(basePackages = {"com.ljx.boot.server.dao"})
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class, args);
}
}
application.properties中配置mapper.xml的路径已经mybatis别名的路径(entity)
mybatis.type-aliases-package=com.ljx.boot.server.entity
mybatis.mapperLocations=classpath:mapper/*.xml
7.启动测试
项目结构图