【SpringBoot】SpringBoot最精简的设置
比较精简的SpringBoot2 设置,包含能力:提供RestFul、JDBC、Log4j2
POM文件设置:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion><!-- 排除SpringBoot自带的Logback日志框架 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
<!-- jdbc begin --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <!-- jdbc 整合end --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
application.properties 文件配置:
server.port=8006 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/XXXDB?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=XXX spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.default-auto-commit = false logging.config=classpath:log4j2.xml <!-- 指定log4j2的配置文件-->
log4j2.xml 文件配置(摘自网络):
<?xml version="1.0" encoding="UTF-8"?> <!--设置log4j2的自身log级别为OFF --> <Configuration status="OFF"> <Properties> <Property name="app_name">XXXservice</Property> <Property name="log_path">logs/${app_name}</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %M() @%L - %msg%n" /> </Console> <File name="ERROR" fileName="${log_path}/error.log" append="false"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %M() @%L - %msg%n" /> </File> <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 --> <RollingFile name="RollingFile" fileName="${log_path}/app.log" filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"> <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %M() @%L - %msg%n" /> <SizeBasedTriggeringPolicy size="5MB" /> </RollingFile> </Appenders> <Loggers> <Root level="INFO"> <appender-ref ref="Console" /> <appender-ref ref="RollingFile" /> <appender-ref ref="ERROR" /> </Root> </Loggers> </Configuration>
应用程序入口:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement //启动全局事务控制 @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
控制器(Rest请求处理类):
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/rest/test") public class TestController { private Logger logger = LoggerFactory.getLogger(TestController.class); @PostMapping(value = "/a") public String test1(@RequestBody String account) { logger.info("tihs is a info"); logger.warn("tihs is a warn"); logger.error("tihs is a error"); return "test1:post:" + account; } @GetMapping(value = "/a") public String test2() { logger.info("tihs is a info"); logger.warn("tihs is a warn"); logger.error("tihs is a error"); return "test2:get:"; } @GetMapping(value = "/") public String test3() { return "test3:get:"; } @DeleteMapping(value = "/account/{id}") public RestSimpleRsp deleteById(@PathVariable String id) { return null; } @PutMapping(value = "/account") public RestRsp<AccountMO> modify(@RequestBody AccountMO account) { return null; } @PostMapping(value = "/account") public RestRsp<AccountMO> add(@RequestBody AccountMO account) { return null; } @PostMapping(value = "/accounts") public RestRsp<AccountMO> getList(@RequestBody QueryParam queryParam) { return null; } }
DAO编写:
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class SysOperatorDao { @Autowired protected JdbcTemplate jdbcTemplate; public String addSysOperator(SysOperatorMO mo) { String sql = "insert into " + SysOperatorMO.getTableName() + "(id,username,password,name,wxCode,email,mobile) values(?,?,?,?,?,?,?)"; int ret = jdbcTemplate.update(sql, new Object[] { mo.getId(), mo.getUsername(), mo.getPassword(), mo.getName(), mo.getWxCode(), mo.getEmail(), mo.getMobile() }); if (ret != 1) { return null; } return mo.getId(); } public boolean modifySysOperator(SysOperatorMO mo) { String sql = "update " + SysOperatorMO.getTableName() + " set name = ?,wxCode = ?,email = ?,mobile = ? where id = ?"; int ret = jdbcTemplate.update(sql, new Object[] { mo.getName(), mo.getWxCode(), mo.getEmail(), mo.getMobile(), mo.getId() }); return ret == 1; } public boolean deleteSysOperator(String id) { String sql = "delete from " + SysOperatorMO.getTableName() + " where id = ?"; int ret = jdbcTemplate.update(sql, new Object[] { id }); return ret == 1; } /** * 查询系统操作人员列表 * * @param queryParam * 查询参数 * @param mos * 返回列表信息(当前这一批,不是全部数据) * @return 总记录数 */ public int getSysOperatorList(QueryParam queryParam, List<SysOperatorMO> mos) { String sql = "select count(*) totalNum," + SysOperatorMO.getDefaultQueryFields() + " from " + SysOperatorMO.getTableName(); return -1; } }
注:
1、应用程序入口类需放在根package中,因为Controller、Component等组件的扫描是从Application所在的包往下递归的
2、官方的向导中依赖了 spring-boot-starter ,引入Log4j2时各种报错,干掉就好了!
南京小黄猫教育
是专业的计算机编程培训,包含面向少儿的Scratch,面向青少年的Python,面向就业的Java、C/C++及Web前端技术。微信:wuwy233
地址:南京市江宁区月华路12-6弘阳上院