# spring-boot-learning **Repository Path**: tdswee/spring-boot-learning ## Basic Information - **Project Name**: spring-boot-learning - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-09-07 - **Last Updated**: 2021-11-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # spring-boot-learning 1.概述 spring boot 2.核心 ###3.核心注解(Annotation) @Configuration @EnableAutoConfiguration @ComponentScan @Configuration 相当于传统的xml配置文件 @ComponentScan 表示将该类自动发现(扫描)并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Component,@Service,@Repository,@Controller等注解的类。 @EnableAutoConfiguration Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。 例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。 你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。 如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。 SpringBoot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象。 因为启动类不能直接放在main/java文件夹下,必须要建一个包把它放进去或者使用@ComponentScan指明要扫描的包。 @SpringBootApplication 申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。 @EnableWebMvc @EnableWebMvc 用于启用Spring MVC的,它能够为使用 @RequestMapping 来传入请求映射到一定的方法 @Controller -annotated类的支持,Spring Boot与标准的Spring MVC不兼容@EnableWebMvc。添加注释时会禁用spring启动自动配置。 @ResponseBody 该注解修饰的函数,会将结果直接填充到HTTP的响应体中,一般用于构建RESTful的api,该注解一般会配合@RequestMapping一起使用。 @Controller 用于定义控制器类, @RestController restfull服务使用 @ResponseBody和@Controller的合集 @ControllerAdvice 全局异常处理 #### 四、JdbcTemplate和Spring-data-jpa,redis 使用 Spring Boot的配置单数据源 @Configration @Bean(name = "dataSource") @ConfigurationProperties(prefix = "sys.druid") public DataSource dataSource() { return new DriverManagerDataSource(); } application.properties自定义配置:阿里巴巴的数据池管理数据源 sys: druid: url: jdbc:mysql://127.0.0.1:3306/y_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver initialSize: 3 minIdle: 3 maxActive: 20 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select '1+1' testWhileIdle: true 默认的配置数据源: spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/gs-jdbc username: root password: initialize: true jdbcTemplate 使用 @Autowired private JdbcTemplate jdbcTemplate; redist 使用 @Bean @ConfigurationProperties(prefix = "spring.redis") JedisConnectionFactory jedisConnectionFactory() { return new JedisConnectionFactory(); } application.properties spring: redis: hostName: 127.0.0.1 password: port: 6379 参考:https://github.com/netgloo/spring-boot-samples ####五、模板引擎Thymeleaf使用 FreeMarker,Groovy,Thymeleaf,Velocity Spring Boot默认就是使用thymeleaf模板引擎的,所以只需要在pom.xml加入依赖即可 一、资源文件的约定目录结构 (默认结构) Maven的资源文件目录:/src/java/resources spring-boot项目静态文件目录:/src/java/resources/static spring-boot项目模板文件目录:/src/java/resources/templates spring-boot静态首页的支持,即index.html放在以下目录结构会直接映射到应用的根目录下: 二、Maven配置 org.springframework.boot spring-boot-starter-thymeleaf 三、开发时修改thymeleaf模板自动重新加载配置 Spring-boot使用thymeleaf时默认是有缓存的,即你把一个页面代码改了不会刷新页面的效果,你必须重新运行spring-boot的main()方法才能看到页面更改的效果。我们可以把thymeleaf的缓存关掉,用于支持页面修改后重新发布到spring-boot内嵌的tomcat中去。在application.properties配置文件中加入以下配置。 application.properties进行配置即可:THYMELEAF (ThymeleafAutoConfiguration) spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false (开发是配置) 参考:http://blog.csdn.net/u014695188/article/details/52347318 #### 七、Filter和全局的异常处理 filter 使用,实现了Filter的接口的类 全局的异常处理,比如HTTP的异常404, 505等等。比如404,默认Spring Boot会返回"Whitelabel Error Page"页面,但是我需要把这个错误页面统一以JSON格式返回。 使用@ControllerAdvice注解新建类处理 //@ExceptionHandler(value={RuntimeException.class,Exception.class})//处理自定义的异常类型 @ExceptionHandler//处理所有异常 @ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定 public GlobalExceptionResponse exceptionHandler(Exception e, HttpServletResponse response) { GlobalExceptionResponse resp = new GlobalExceptionResponse(); logger.error("#系统错误{}",e); e.printStackTrace(); resp.setErrorCode("500"); resp.setErrorMsg("系统错误"); response.setStatus(500); return resp; } 参考:https://github.com/broly8/SpringBootGlobalExceptionHandler #### 八、日志 在Spring Boot 中记录日志只需两步: 1、在 src/main/resources 下面创建logback.xml 文件,并按上面讲述的进行配置。 或者使用最简单的方法在 application 配置文件中配置。 2、在Java代码中创建实例,并在需要输出日志的地方使用。 // 在Java类中创建 logger 实例 private Logger logger = LoggerFactory.getLogger(this.getClass()); #### 九、服务化部署 jar 服务启动(内置tomcat/jetty) 1.创建服务路径 chmod 500 your-app.jar sudo chattr +i your-app.jar 2.创建系统服务 sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp ### 应用的进程管理器pm2部署 *.json 配置 { "apps": [{ "name": "JavaAgent", "cwd": "/usr/bin", "args": [ "-Xmx256m", "-jar", "-Dspring.profiles.active=dev", "/Users/wyz/Documents/msg-1.0-SNAPSHOT.jar", "com.yun.MsgApplication" ], "env": { "ANYENVVARIABLE": "dev" }, "script": "java", "nodeargs": [], "logdateformat": "YYYY-MM-DD HH:mm Z", "execinterpreter": "none", "exec_mode": "fork" } ]}