所需要的Maven的jar包依赖

引用网址:初识Spring Boot框架


一、所需的jar包依赖

spring-boot-starter-parent
提供dependency management也就是依赖管理,引入之后声明其他的dependency的时候就不需要version了

spring-boot-starter-web
springweb的核心组件

spring-boot-maven-plugin
如果我们要直接Main启动spring,那么以下的plugin必须要添加,否则也是无法启动的。如果使用maven 的spring-boot:run的话是不需要此配置的。

举例

一、创建一个MyController类

  1. @RestController
  2. @EnableAutoConfiguration
  3. public class MyController{
  4. @RequestMapping("/my")
  5. public String index() {
  6. return "Hello World";
  7. }
  8. public static void main(String[] args) {
  9. SpringApplication.run(MyController.class, args);
  10. }
  11. }

二、注解

  • @RestController

    • 在上加上RestController表示修饰该Controller所有的方法返回Json格式,可以直接编写其Restful接口。
  • @EnableAutoConfiguration

    • 表示让SpringBoot 根据类路径中的jar包依赖为当前项目进行自动配置。
  • @ComponentScan

    • 告诉Spring的哪个packages的用注解标识的类,会被spring自动扫描并装入bean容器。
  • @SpringBootConfiguration

    • 它就相当于@Configuration注解,表示这个类是一个配置类。
  • @SpringBootApplication

    • 它组合了@SpringBootConfiguration和@EnableAutoConfiguration和@ComponentScan注解。如果我们不使用@SpringBootApplication那么我们就需要使用以上三个注解了。

    • 唯一需要注意的是如果我们使用了@SpringBootApplication注解的话,系统会去入口类的同级包以及下级包去扫描实体类,因此我们建议入口类的位置在groupld+arctifactID的包名下。

注意: SpringBoot的默认端口号为8080

三、Web开发

  • 1、静态资源引用

    • 默认配置

      • Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
        /static
        /public
        /resources
        /META-INF/resources
        举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
  • 2、全局捕获异常

    • @ExceptionHandler表示拦截异常。
    • @ControllerAdvice 时一个Controller的辅助类,最常用的就是作为全局异常处理的切面类。
    • @ControllerAdvice 可以指定扫描范围。
    • @ControllerAdvice 约定了几种返回值,如果是直接范围model类的话,需要使用@ResponseBody进行json转换。

栗子如下:

  1. /**
  2. *全局捕获异常
  3. */
  4. @ControllerAdvice
  5. public class GlobalExceptionHandler {
  6. @ExceptionHandler(RuntimeException.class)
  7. @ResponseBody
  8. public Map<String, Object> exceptionHandler() {
  9. Map<String, Object> map = new HashMap<String, Object>();
  10. map.put("errorCode", "101");
  11. map.put("errorMsg", "系統错误!");
  12. return map;
  13. }
  14. }
  • 3、渲染Web页面

    • SpringBoot模板引擎

      • Thymeleaf

      • FreeMarker

      • Velocity

      • Groovy

      • Mustache

      • SpringBoot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现SpringBoot的多种特性。

      • 当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径。

3.4.3、前台代码

  1. </#if>
  2. <#list userlist as user>
  3. ${user}
  4. </#list>

3.4.5、Freemarker配置

新建application.properties文件

  1. ########################################################
  2. ###FREEMARKER (FreeMarkerAutoConfiguration)
  3. ########################################################
  4. spring.freemarker.allow-request-override=false
  5. spring.freemarker.cache=true
  6. spring.freemarker.check-template-location=true
  7. spring.freemarker.charset=UTF-8
  8. spring.freemarker.content-type=text/html
  9. spring.freemarker.expose-request-attributes=false
  10. spring.freemarker.expose-session-attributes=false
  11. spring.freemarker.expose-spring-macro-helpers=false
  12. #spring.freemarker.prefix=
  13. #spring.freemarker.request-context-attribute=
  14. #spring.freemarker.settings.*=
  15. spring.freemarker.suffix=.ftl
  16. spring.freemarker.template-loader-path=classpath:/templates/
  17. #comma-separated list
  18. #spring.freemarker.view-names= # whitelist of view names that can be resolved

3.5、使用JSP渲染Web视图

3.5.1、pom文件引入以下依赖

  1. org.springframework.boot
  2. spring-boot-starter-parent
  3. 1.3.3.RELEASE
  4. org.springframework.boot
  5. spring-boot-starter-web
  6. org.springframework.boot
  7. spring-boot-starter-tomcat
  8. org.apache.tomcat.embed
  9. tomcat-embed-jasper

3.5.2、在application.properties创建以下配置

  1. spring.mvc.view.prefix=/WEB-INF/jsp/
  2. spring.mvc.view.suffix=.jsp

3.5.3、后台代码

  1. @Controller
  2. public class IndexController {
  3. @RequestMapping("/index")
  4. public String index() {
  5. return "index";
  6. }
  7. }

四、数据访问

4.1、springboot整合使用JdbcTemplate

  1. 4.1.1 pom文件引入
  2. org.springframework.boot
  3. spring-boot-starter-parent
  4. 1.5.2.RELEASE
  5. org.springframework.boot
  6. spring-boot-starter-jdbc
  7. mysql
  8. mysql-connector-java
  9. 5.1.21
  10. org.springframework.boot
  11. spring-boot-starter-test
  12. test
  13. org.springframework.boot
  14. spring-boot-starter-web

4.1.2 application.properties新增配置

  1. spring.datasource.url=jdbc:mysql://localhost:3306/test
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4.1.3 UserService类

  1. @Service
  2. public class UserServiceImpl implements UserService {
  3. @Autowired
  4. private JdbcTemplate jdbcTemplate;
  5. public void createUser(String name, Integer age) {
  6. System.out.println("ssss");
  7. jdbcTemplate.update("insert into users values(null,?,?);", name, age);
  8. }
  9. }

4.1.4 App类

  1. @ComponentScan(basePackages = "com.itmayiedu")
  2. @EnableAutoConfiguration
  3. public class App {
  4. public static void main(String[] args) {
  5. SpringApplication.run(App.class, args);
  6. }
  7. }

注意: spring-boot-starter-parent要在1.5以上

四、springboot整合使用mybatis

4.1、pom文件引入

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.3.2.RELEASE</version>
  5. <relativePath /> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-test</artifactId>
  15. <scope>test</scope>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.mybatis.spring.boot</groupId>
  19. <artifactId>mybatis-spring-boot-starter</artifactId>
  20. <version>1.1.1</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>5.1.21</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-web</artifactId>
  30. </dependency>
  31. </dependencies>

4.2、配置文件引入

  1. spring.datasource.url=jdbc:mysql://localhost:3306/test
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4.3、Mapper代码

  1. public interface UserMapper {
  2. @Select("SELECT * FROM USERS WHERE NAME = #{name}")
  3. User findByName(@Param("name") String name);
  4. @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
  5. int insert(@Param("name") String name, @Param("age") Integer age);
  6. }

4.4、启动方式

  1. @ComponentScan(basePackages = "com.itmayiedu")
  2. @MapperScan(basePackages = "com.itmayiedu.mapper")
  3. @SpringBootApplication
  4. public class App {
  5. public static void main(String[] args) {
  6. SpringApplication.run(App.class, args);
  7. }
  8. }

五、springboot整合使用springjpa

5.1、pom文件引入依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.4.2.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-data-jpa</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>mysql</groupId>
  13. <artifactId>mysql-connector-java</artifactId>
  14. <version>5.1.21</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. </dependencies>

5.2、创建User实体类

  1. @Entity(name = "users")
  2. public class User {
  3. @Id
  4. @GeneratedValue
  5. private Integer id;
  6. @Column
  7. private String name;
  8. @Column
  9. private Integer age;
  10. // ..get/set方法
  11. }

5.3、创建UserDao

  1. public interface UserDao extends JpaRepository<User, Integer> {
  2. }

5.4、创建IndexController

  1. @RestController
  2. public class IndexController {
  3. @Autowired
  4. private UserDao userDao;
  5. @RequestMapping("/index")
  6. public String index(Integer id) {
  7. User findUser = userDao.findOne(id);
  8. System.out.println(findUser.getName());
  9. return "success";
  10. }
  11. }

5.5、启动项目

  1. @ComponentScan(basePackages = { "com.itmayiedu" })
  2. @EnableJpaRepositories(basePackages = "com.itmayiedu.dao")
  3. @EnableAutoConfiguration
  4. @EntityScan(basePackages = "com.itmayiedu.entity")
  5. public class App {
  6. public static void main(String[] args) {
  7. SpringApplication.run(App.class, args);
  8. }
  9. }

六、springboot整合多数据源

6.1、配置文件中新增两个数据源

  1. spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
  2. spring.datasource.test1.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
  3. spring.datasource.test1.username = root
  4. spring.datasource.test1.password = root
  5. spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
  6. spring.datasource.test2.url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
  7. spring.datasource.test2.username = root
  8. spring.datasource.test2.password = root

6.2、配置文件中新增两个数据源

  1. @Configuration // 注册到springboot容器中
  2. @MapperScan(basePackages = "com.itmayiedu.user1", sqlSessionFactoryRef = "test1SqlSessionFactory")
  3. public class DataSource1Config {
  4. /**
  5. *
  6. * @methodDesc: 功能描述:(配置test1数据库)
  7. * @param: @return
  8. * @returnType:@return DataSource
  9. */
  10. @Bean(name = "test1DataSource")
  11. @Primary
  12. @ConfigurationProperties(prefix = "spring.datasource.test1")
  13. public DataSource testDataSource() {
  14. return DataSourceBuilder.create().build();
  15. }
  16. /**
  17. *
  18. * @methodDesc: 功能描述:(test1 sql会话工厂)
  19. * @param: @param
  20. * dataSource
  21. * @param: @return
  22. * @param: @throws
  23. * Exception
  24. * @returnType:@param dataSource
  25. * @returnType:@return
  26. * @returnType:@throws Exception SqlSessionFactory
  27. */
  28. @Bean(name = "test1SqlSessionFactory")
  29. @Primary
  30. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
  31. throws Exception {
  32. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  33. bean.setDataSource(dataSource);
  34. // bean.setMapperLocations(
  35. // new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
  36. return bean.getObject();
  37. }
  38. /**
  39. *
  40. * @methodDesc: 功能描述:(test1 事物管理)
  41. * @param: @param
  42. * dataSource
  43. * @param: @return
  44. * @param: @throws
  45. * Exception
  46. * @returnType:@param dataSource
  47. * @returnType:@return
  48. * @returnType:@throws Exception SqlSessionFactory
  49. */
  50. @Bean(name = "test1TransactionManager")
  51. @Primary
  52. public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
  53. return new DataSourceTransactionManager(dataSource);
  54. }
  55. @Bean(name = "test1SqlSessionTemplate")
  56. public SqlSessionTemplate testSqlSessionTemplate(
  57. @Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  58. return new SqlSessionTemplate(sqlSessionFactory);
  59. }
  60. }

6.3、创建分包Mapper

  1. public interface User1Mapper {
  2. @Insert("insert into users values(null,#{name},#{age});")
  3. public int addUser(@Param("name") String name, @Param("age") Integer age);
  4. }

6.4、启动项目

  1. @ComponentScan(basePackages = "com.itmayiedu")
  2. @EnableAutoConfiguration
  3. public class App {
  4. public static void main(String[] args) {
  5. SpringApplication.run(App.class, args);
  6. }
  7. }

七、事务管理

7.1、springboot整合事物管理

springboot默认集成事物,只主要在方法上加上@Transactional即可

7.2、SpringBoot分布式事物管理

使用springboot+jta+atomikos 分布式事物管理

7.3、新增配置文件信息

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jta-atomikos</artifactId>
  4. </dependency>

7.4、新增配置文件信息

  1. # Mysql 1
  2. mysql.datasource.test.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
  3. mysql.datasource.test.username = root
  4. mysql.datasource.test.password = root
  5. mysql.datasource.test.minPoolSize = 3
  6. mysql.datasource.test.maxPoolSize = 25
  7. mysql.datasource.test.maxLifetime = 20000
  8. mysql.datasource.test.borrowConnectionTimeout = 30
  9. mysql.datasource.test.loginTimeout = 30
  10. mysql.datasource.test.maintenanceInterval = 60
  11. mysql.datasource.test.maxIdleTime = 60
  12. mysql.datasource.test.testQuery = select 1
  13. # Mysql 2
  14. mysql.datasource.test2.url =jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
  15. mysql.datasource.test2.username =root
  16. mysql.datasource.test2.password =root
  17. mysql.datasource.test2.minPoolSize = 3
  18. mysql.datasource.test2.maxPoolSize = 25
  19. mysql.datasource.test2.maxLifetime = 20000
  20. mysql.datasource.test2.borrowConnectionTimeout = 30
  21. mysql.datasource.test2.loginTimeout = 30
  22. mysql.datasource.test2.maintenanceInterval = 60
  23. mysql.datasource.test2.maxIdleTime = 60
  24. mysql.datasource.test2.testQuery = select 1

7.5、读取配置文件信息

  1. package com.itmayiedu.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. @ConfigurationProperties(prefix = "mysql.datasource.test")
  4. public class DBConfig1 {
  5. private String url;
  6. private String username;
  7. private String password;
  8. private int minPoolSize;
  9. private int maxPoolSize;
  10. private int maxLifetime;
  11. private int borrowConnectionTimeout;
  12. private int loginTimeout;
  13. private int maintenanceInterval;
  14. private int maxIdleTime;
  15. private String testQuery;
  16. }
  17. package com.itmayiedu.config;
  18. import org.springframework.boot.context.properties.ConfigurationProperties;
  19. @ConfigurationProperties(prefix = "mysql.datasource.test1")
  20. public class DBConfig2 {
  21. private String url;
  22. private String username;
  23. private String password;
  24. private int minPoolSize;
  25. private int maxPoolSize;
  26. private int maxLifetime;
  27. private int borrowConnectionTimeout;
  28. private int loginTimeout;
  29. private int maintenanceInterval;
  30. private int maxIdleTime;
  31. private String testQuery;
  32. }

7.6、创建多数据源

  1. @Configuration
  2. // basePackages 最好分开配置 如果放在同一个文件夹可能会报错
  3. @MapperScan(basePackages = "com.itmayiedu.test01", sqlSessionTemplateRef = "testSqlSessionTemplate")
  4. public class TestMyBatisConfig1 {
  5. // 配置数据源
  6. @Primary
  7. @Bean(name = "testDataSource")
  8. public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {
  9. MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
  10. mysqlXaDataSource.setUrl(testConfig.getUrl());
  11. mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
  12. mysqlXaDataSource.setPassword(testConfig.getPassword());
  13. mysqlXaDataSource.setUser(testConfig.getUsername());
  14. mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
  15. AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
  16. xaDataSource.setXaDataSource(mysqlXaDataSource);
  17. xaDataSource.setUniqueResourceName("testDataSource");
  18. xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());
  19. xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());
  20. xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());
  21. xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());
  22. xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());
  23. xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());
  24. xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());
  25. xaDataSource.setTestQuery(testConfig.getTestQuery());
  26. return xaDataSource;
  27. }
  28. @Bean(name = "testSqlSessionFactory")
  29. public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource)
  30. throws Exception {
  31. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  32. bean.setDataSource(dataSource);
  33. return bean.getObject();
  34. }
  35. @Bean(name = "testSqlSessionTemplate")
  36. public SqlSessionTemplate testSqlSessionTemplate(
  37. @Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  38. return new SqlSessionTemplate(sqlSessionFactory);
  39. }
  40. }
  41. package com.itmayiedu.datasource;
  42. import java.sql.SQLException;
  43. import javax.sql.DataSource;
  44. import org.apache.ibatis.session.SqlSessionFactory;
  45. import org.mybatis.spring.SqlSessionFactoryBean;
  46. import org.mybatis.spring.SqlSessionTemplate;
  47. import org.mybatis.spring.annotation.MapperScan;
  48. import org.springframework.beans.factory.annotation.Qualifier;
  49. import org.springframework.context.annotation.Bean;
  50. import org.springframework.context.annotation.Configuration;
  51. import com.atomikos.jdbc.AtomikosDataSourceBean;
  52. import com.itmayiedu.config.DBConfig1;
  53. import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;
  54. @Configuration
  55. // basePackages 最好分开配置 如果放在同一个文件夹可能会报错
  56. @MapperScan(basePackages = "com.itmayiedu.test02", sqlSessionTemplateRef = "test2SqlSessionTemplate")
  57. public class TestMyBatisConfig2 {
  58. // 配置数据源
  59. @Bean(name = "test2DataSource")
  60. public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {
  61. MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
  62. mysqlXaDataSource.setUrl(testConfig.getUrl());
  63. mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
  64. mysqlXaDataSource.setPassword(testConfig.getPassword());
  65. mysqlXaDataSource.setUser(testConfig.getUsername());
  66. mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
  67. AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
  68. xaDataSource.setXaDataSource(mysqlXaDataSource);
  69. xaDataSource.setUniqueResourceName("test2DataSource");
  70. xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());
  71. xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());
  72. xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());
  73. xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());
  74. xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());
  75. xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());
  76. xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());
  77. xaDataSource.setTestQuery(testConfig.getTestQuery());
  78. return xaDataSource;
  79. }
  80. @Bean(name = "test2SqlSessionFactory")
  81. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
  82. throws Exception {
  83. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  84. bean.setDataSource(dataSource);
  85. return bean.getObject();
  86. }
  87. @Bean(name = "test2SqlSessionTemplate")
  88. public SqlSessionTemplate testSqlSessionTemplate(
  89. @Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  90. return new SqlSessionTemplate(sqlSessionFactory);
  91. }
  92. }

7.7、启动加载配置

  1. @EnableConfigurationProperties(value = { DBConfig1.class, DBConfig2.class })

八、日志管理

8.1、使用log4j记录日志

  1. #log4j.rootLogger=CONSOLE,info,error,DEBUG
  2. log4j.rootLogger=info,error,CONSOLE,DEBUG
  3. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
  4. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
  6. log4j.logger.info=info
  7. log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
  8. log4j.appender.info.layout=org.apache.log4j.PatternLayout
  9. log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
  10. log4j.appender.info.datePattern='.'yyyy-MM-dd
  11. log4j.appender.info.Threshold = info
  12. log4j.appender.info.append=true
  13. #log4j.appender.info.File=/home/admin/pms-api-services/logs/info/api_services_info
  14. log4j.appender.info.File=/Users/dddd/Documents/testspace/pms-api-services/logs/info/api_services_info
  15. log4j.logger.error=error
  16. log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
  17. log4j.appender.error.layout=org.apache.log4j.PatternLayout
  18. log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
  19. log4j.appender.error.datePattern='.'yyyy-MM-dd
  20. log4j.appender.error.Threshold = error
  21. log4j.appender.error.append=true
  22. #log4j.appender.error.File=/home/admin/pms-api-services/logs/error/api_services_error
  23. log4j.appender.error.File=/Users/dddd/Documents/testspace/pms-api-services/logs/error/api_services_error
  24. log4j.logger.DEBUG=DEBUG
  25. log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender
  26. log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
  27. log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
  28. log4j.appender.DEBUG.datePattern='.'yyyy-MM-dd
  29. log4j.appender.DEBUG.Threshold = DEBUG
  30. log4j.appender.DEBUG.append=true
  31. #log4j.appender.DEBUG.File=/home/admin/pms-api-services/logs/debug/api_services_debug
  32. log4j.appender.DEBUG.File=/Users/dddd/Documents/testspace/pms-api-services/logs/debug/api_services_debug

8.2、使用AOP统一处理Web请求日志

8.2.1、POM文件新增依赖
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

8.2.2、POM文件新增依赖
  1. @Aspect
  2. @Component
  3. public class WebLogAspect {
  4. private Logger logger = LoggerFactory.getLogger(getClass());
  5. @Pointcut("execution(public * com.itmayiedu.controller..*.*(..))")
  6. public void webLog() {
  7. }
  8. @Before("webLog()")
  9. public void doBefore(JoinPoint joinPoint) throws Throwable {
  10. // 接收到请求,记录请求内容
  11. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  12. HttpServletRequest request = attributes.getRequest();
  13. // 记录下请求内容
  14. logger.info("URL : " + request.getRequestURL().toString());
  15. logger.info("HTTP_METHOD : " + request.getMethod());
  16. logger.info("IP : " + request.getRemoteAddr());
  17. Enumeration<String> enu = request.getParameterNames();
  18. while (enu.hasMoreElements()) {
  19. String name = (String) enu.nextElement();
  20. logger.info("name:{},value:{}", name, request.getParameter(name));
  21. }
  22. }
  23. @AfterReturning(returning = "ret", pointcut = "webLog()")
  24. public void doAfterReturning(Object ret) throws Throwable {
  25. // 处理完请求,返回内容
  26. logger.info("RESPONSE : " + ret);
  27. }
  28. }

九、缓存支持

9.1、注解配置与EhCache使用

9.1.1、POM文件引入

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>

9.1.2、新建ehcache.xml 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
  4. updateCheck="false">
  5. <diskStore path="java.io.tmpdir/Tmp_EhCache" />
  6. <!-- 默认配置 -->
  7. <defaultCache maxElementsInMemory="5000" eternal="false"
  8. timeToIdleSeconds="120" timeToLiveSeconds="120"
  9. memoryStoreEvictionPolicy="LRU" overflowToDisk="false" />
  10. <cache name="baseCache" maxElementsInMemory="10000"
  11. maxElementsOnDisk="100000" />
  12. </ehcache>

配置信息介绍

  1. <!--
  2. 2. name:缓存名称。
  3. 3. maxElementsInMemory:缓存最大个数。
  4. 4. eternal:对象是否永久有效,一但设置了,timeout将不起作用。
  5. 5. timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  6. 6. timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  7. 7. overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  8. 8. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  9. 9. maxElementsOnDisk:硬盘最大缓存个数。
  10. 10. diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
  11. 11. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  12. 12. memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
  13. 13. clearOnFlush:内存数量最大时是否清除。
  14. 14. -->

9.1.3、代码使用Cacheable

  1. @CacheConfig(cacheNames = "baseCache")
  2. public interface UserMapper {
  3. @Select("select * from users where name=#{name}")
  4. @Cacheable
  5. UserEntity findName(@Param("name") String name);
  6. }

9.1.4、清除缓存

  1. @Autowired
  2. private CacheManager cacheManager;
  3. @RequestMapping("/remoKey")
  4. public void remoKey() {
  5. cacheManager.getCache("baseCache").clear();
  6. }

十、其他内容

10.1、使用@Scheduled创建定时任务

在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置

  1. @Component
  2. public class ScheduledTasks {
  3. private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
  4. @Scheduled(fixedRate = 5000)
  5. public void reportCurrentTime() {
  6. System.out.println("现在时间:" + dateFormat.format(new Date()));
  7. }
  8. }

10.2、使用@Async实现异步调用

启动加上@EnableAsync ,需要执行异步方法上加入 @Async

10.3、自定义参数

配置文件值

  1. name=itmayiedu.com

配置文件值

  1. @Value("${name}")
  2. private String name;
  3. @ResponseBody
  4. @RequestMapping("/getValue")
  5. public String getValue() {
  6. return name;
  7. }

10.4、多环境配置

  1. spring.profiles.active=pre
  1. application-dev.properties:开发环境
  2. application-test.properties:测试环境
  3. application-prod.properties:生产环境

10.5、修改端口号

  1. server.port=8888
  2. server.context-path=/itmayiedu

10.6、SpringBoot yml 使用

10.6.1、创建application.yml

  1. server:
  2. port: 8090
  3. context-path: /itmayiedu

10.7、发布打包

使用mvn package 打包
使用java –jar 包名
如果报错没有主清单,在pom文件中新增

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-compiler-plugin</artifactId>
  6. <configuration>
  7. <source>1.8</source>
  8. <target>1.8</target>
  9. </configuration>
  10. </plugin>
  11. <plugin>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-maven-plugin</artifactId>
  14. <configuration>
  15. <maimClass>com.itmayiedu.app.App</maimClass>
  16. </configuration>
  17. <executions>
  18. <execution>
  19. <goals>
  20. <goal>repackage</goal>
  21. </goals>
  22. </execution>
  23. </executions>
  24. </plugin>
  25. </plugins>
  26. </build>