标签:gem live 实现 mvc path round web页面 修改端口号 char
在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用Spring Boot来让你更易上手,更简单快捷地构建Spring应用!
Spring Boot让我们的Spring应用变的更轻量化。比如:你可以仅仅依靠一个Java类来运行一个Spring引用。你也可以打包你的应用为jar并通过使用java -jar来运行你的Spring Web应用。
Spring Boot的主要优点:
为所有Spring开发者更快的入门
开箱即用,提供各种默认配置来简化项目配置
内嵌式容器简化Web项目
没有冗余代码生成和XML配置的要求
本章主要目标完成Spring Boot基础项目的构建,并且实现一个简单的Http请求处理,通过这个例子对Spring Boot有一个初步的了解,并体验其结构简单、开发快速的特性。
Java1.8及以上
Spring Framework 4.1.5及以上
本文采用Java 1.8.0_73、Spring Boot 1.3.2调试通过。
名为”springboot-helloworld” 类型为Jar工程项目
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <!—SpringBoot web 组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
spring-boot-starter-parent作用:
在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。
spring-boot-starter-web作用:
springweb 核心组件
spring-boot-maven-plugin作用:
如果我们要直接Main启动spring,那么以下plugin必须要添加,否则是无法启动的。如果使用maven 的spring-boot:run的话是不需要此配置的。(我在测试的时候,如果不配置下面的plugin也是直接在Main中运行的。)
创建package命名为com.itmayiedu.controller(根据实际情况修改)
创建HelloController类,内容如下
package com.hongmoshui.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } }
在上加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口
注解:作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置
这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。
标识为启动类
Springboot默认端口号为8080
package com.hongmoshui.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } }
启动主程序,打开浏览器访问http://localhost:8080/index,可以看到页面输出Hello World
package com.hongmoshui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.hongmoshui.test") // 控制器扫包范围 @EnableAutoConfiguration public class TestApp { public static void main(String[] args) { SpringApplication.run(TestApp.class, args); } }
在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
默认配置
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
@ExceptionHandler 表示拦截异常
package com.hongmoshui.test; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String, Object> exceptionHandler() { Map<String, Object> map = new HashMap<String, Object>(); map.put("errorCode", "101"); map.put("errorMsg", "系統错误!"); return map; } }
渲染Web页面
在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?
模板引擎
在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供了默认配置的模板引擎主要有以下几种:
Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
<!-- 引入freeMarker的依赖包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
在src/main/resources/创建一个templates文件夹,后缀为test.ftl
<!DOCTYPE html> <html> <head lang="CN"> <meta charset="UTF-8" /> <title></title> </head> <body> ${name} </body> </html>
package com.hongmoshui.test; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @RequestMapping("/test") public String test(Map<String, Object> map) { map.put("name", "美丽的天使..."); return "test"; } }
后端代码:
@RequestMapping("/freemarkerTest") public String index(Map<String, Object> result) { result.put("name", "hongmoshui"); result.put("sex", "1"); List<String> userList = new ArrayList<String>(); userList.add("zhangsan"); userList.add("lisi"); userList.add("wangwu"); result.put("userList", userList); return "freemarkerTest"; }
前端代码:
<!DOCTYPE html> <html> <head lang="CN"> <meta charset="UTF-8" /> <title>freemaker测试页</title> </head> <body> ${name}<br/> <#if sex=="1"> 男 <#elseif sex=="2"> 女 <#else> 其他 </#if><br/> <#list userList as user> ${user}<br/> </#list> </body> </html>
新建application.properties文件
######################################################## ###FREEMARKER (FreeMarkerAutoConfiguration) ######################################################## spring.freemarker.allow-request-override=false spring.freemarker.cache=true spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false #spring.freemarker.prefix= #spring.freemarker.request-context-attribute= #spring.freemarker.settings.*= spring.freemarker.suffix=.ftl spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list #spring.freemarker.view-names= # whitelist of view names that can be resolved
<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> <groupId>com.hongmoshui.www</groupId> <artifactId>springBoot-jsp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> </dependencies> </project>
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
package com.hongmoshui.test.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @RequestMapping("/test") public String index() { System.out.println("测试页面,哈哈哈哈哈哈哈"); return "test"; } }
package com.hongmoshui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TestJspApp { public static void main(String[] args) { SpringApplication.run(TestJspApp.class, args); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test page</title> </head> <body>测试页面(创建项目一定要为war类型) </body> </html>
注意:创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
spring.datasource.url=jdbc:mysql://localhost:23306/mydatabase spring.datasource.username=root spring.datasource.password=master spring.datasource.driver-class-name=com.mysql.jdbc.Driver
package com.hongmoshui.test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.hongmoshui.test.service.UserService; @Controller public class TestController { @Autowired UserService userService; @RequestMapping("/createUser") @ResponseBody public String createUser(String name, Integer age) { if (name == null || age == null) { return "parameter is error"; } int result = userService.createUser(name, age); return result > 0 ? "success" : "fail"; } }
package com.hongmoshui.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import com.hongmoshui.test.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private JdbcTemplate jdbcTemplate; public int createUser(String name, Integer age) { System.out.println("create user,name:" + name + ",age:" + age); int update = jdbcTemplate.update("insert into users values(null,?,?);", name, age); return update; } }
package com.hongmoshui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.hongmoshui.test") // 控制器扫包范围 @EnableAutoConfiguration public class TestApp { public static void main(String[] args) { SpringApplication.run(TestApp.class, args); } }
注意: spring-boot-starter-parent要在1.5以上
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version>
注意:这个jar包依赖,不能是以下的,不然启动时会报错,无法实例化UserDao
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency>
package com.hongmoshui.test.dao; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.hongmoshui.test.entity.User; @Mapper public interface UserDao { @Select("SELECT * FROM users WHERE name = #{name}") User queryUser(String name); }
package com.hongmoshui; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.hongmoshui.test") // 控制器扫包范围 @EnableAutoConfiguration @MapperScan("com.hongmoshui.test.dao") public class TestApp { public static void main(String[] args) { SpringApplication.run(TestApp.class, args); } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
package com.hongmoshui.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name = "users")
public class User
{
@Id
@GeneratedValue
private int id;
@Column
private String name;
@Column
private int age;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
@Entity(name = "users"):表名【users】,
@Id:表的主键
@GeneratedValue:主键自增
@Column:表的字段属性
package com.hongmoshui.test.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.hongmoshui.test.entity.User; public interface UserDaoJPA extends JpaRepository<User, Integer> { }
package com.hongmoshui; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @ComponentScan(basePackages = "com.hongmoshui.test") // 控制器扫包范围 @EnableAutoConfiguration @MapperScan("com.hongmoshui.test.dao") @EnableJpaRepositories("com.hongmoshui.test.dao") @EntityScan("com.hongmoshui.test.entity") public class TestApp { public static void main(String[] args) { SpringApplication.run(TestApp.class, args); } }
@EnableJpaRepositories("com.hongmoshui.test.dao"):dao的包路径
@EntityScan("com.hongmoshui.test.entity"):实体类的包路径
##test1 spring.datasource.test1.url=jdbc:mysql://localhost:23306/test1 spring.datasource.test1.username=root spring.datasource.test1.password=master spring.datasource.test1.driverClassName=com.mysql.jdbc.Driver ##test2 spring.datasource.test2.url=jdbc:mysql://localhost:23306/test2 spring.datasource.test2.username=root spring.datasource.test2.password=master spring.datasource.test2.driverClassName=com.mysql.jdbc.Driver
数据库test1的配置DataSource1Config.java
package com.hongmoshui.test.datasource.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @Configuration // 注册到springboot容器中 @MapperScan(basePackages = "com.hongmoshui.test.datasource.user.user1", sqlSessionFactoryRef = "test1SqlSessionFactory") public class DataSource1Config { /** * 配置test1数据库 * @author 墨水 */ @Bean(name = "test1DataSource") @Primary // 这个注解表示,默认使用此数据源 @ConfigurationProperties(prefix = "spring.datasource.test1") public DataSource testDataSource() { return DataSourceBuilder.create().build(); } /** * test1 sql会话工厂 * @author 墨水 */ @Bean(name = "test1SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setMapperLocations( // new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); return bean.getObject(); } /** * test1 事物管理 * @author 墨水 */ @Bean(name = "test1TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * test1 sql会话模板 * @author 墨水 */ @Bean(name = "test1SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
数据库test2的配置DataSource2Config.java
package com.hongmoshui.test.datasource.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @Configuration // 注册到springboot容器中 @MapperScan(basePackages = "com.hongmoshui.test.datasource.user.user2", sqlSessionFactoryRef = "test2SqlSessionFactory") public class DataSource2Config { /** * 配置test2数据库 * @author 墨水 */ @Bean(name = "test2DataSource") @ConfigurationProperties(prefix = "spring.datasource.test2") public DataSource testDataSource() { return DataSourceBuilder.create().build(); } /** * test2 sql会话工厂 * @author 墨水 */ @Bean(name = "test2SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setMapperLocations( // new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml")); return bean.getObject(); } /** * test2 事物管理 * @author 墨水 */ @Bean(name = "test2TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * test2 sql会话模板 * @author 墨水 */ @Bean(name = "test2SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
package com.hongmoshui.test.datasource.user.user1; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.hongmoshui.test.datasource.entity.User; public interface User1Mapper { @Insert("insert into users values(null,#{name},#{age});") public int addUser(@Param("name") String name, @Param("age") Integer age); @Select("select * from users where name=#{name};") public User queryUser(String name); }
package com.hongmoshui.test.datasource.user.user2; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.hongmoshui.test.datasource.entity.User; public interface User2Mapper { @Insert("insert into users values(null,#{name},#{age});") public int addUser(@Param("name") String name, @Param("age") Integer age); @Select("select * from users where name=#{name};") public User queryUser(String name); }
package com.hongmoshui.test.datasource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.hongmoshui.test.datasource") @EnableAutoConfiguration public class datasourceApp { public static void main(String[] args) { SpringApplication.run(datasourceApp.class, args); } }
springboot默认集成事物,只主要在方法上加上@Transactional即可
使用springboot+jta+atomikos 分布式事物管理
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency>
# Mysql 1 mysql.datasource.atomikos.test1.url = jdbc:mysql://localhost:23306/test1?useUnicode=true&characterEncoding=utf-8 mysql.datasource.atomikos.test1.username = root mysql.datasource.atomikos.test1.password = master mysql.datasource.atomikos.test1.minPoolSize = 3 mysql.datasource.atomikos.test1.maxPoolSize = 25 mysql.datasource.atomikos.test1.maxLifetime = 20000 mysql.datasource.atomikos.test1.borrowConnectionTimeout = 30 mysql.datasource.atomikos.test1.loginTimeout = 30 mysql.datasource.atomikos.test1.maintenanceInterval = 60 mysql.datasource.atomikos.test1.maxIdleTime = 60 mysql.datasource.atomikos.test1.testQuery = select 1 # Mysql 2 mysql.datasource.atomikos.test2.url =jdbc:mysql://localhost:23306/test2?useUnicode=true&characterEncoding=utf-8 mysql.datasource.atomikos.test2.username =root mysql.datasource.atomikos.test2.password =m mysql.datasource.atomikos.test2.minPoolSize = 3 mysql.datasource.atomikos.test2.maxPoolSize = 25 mysql.datasource.atomikos.test2.maxLifetime = 20000 mysql.datasource.atomikos.test2.borrowConnectionTimeout = 30 mysql.datasource.atomikos.test2.loginTimeout = 30 mysql.datasource.atomikos.test2.maintenanceInterval = 60 mysql.datasource.atomikos.test2.maxIdleTime = 60 mysql.datasource.atomikos.test2.testQuery = select 1
package com.hongmoshui.test.datasource.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mysql.datasource.atomikos.test1") public class DBConfig1 { private String url; private String username; private String password; private int minPoolSize; private int maxPoolSize; private int maxLifetime; private int borrowConnectionTimeout; private int loginTimeout; private int maintenanceInterval; private int maxIdleTime; private String testQuery; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } 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 int getMinPoolSize() { return minPoolSize; } public void setMinPoolSize(int minPoolSize) { this.minPoolSize = minPoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public int getMaxLifetime() { return maxLifetime; } public void setMaxLifetime(int maxLifetime) { this.maxLifetime = maxLifetime; } public int getBorrowConnectionTimeout() { return borrowConnectionTimeout; } public void setBorrowConnectionTimeout(int borrowConnectionTimeout) { this.borrowConnectionTimeout = borrowConnectionTimeout; } public int getLoginTimeout() { return loginTimeout; } public void setLoginTimeout(int loginTimeout) { this.loginTimeout = loginTimeout; } public int getMaintenanceInterval() { return maintenanceInterval; } public void setMaintenanceInterval(int maintenanceInterval) { this.maintenanceInterval = maintenanceInterval; } public int getMaxIdleTime() { return maxIdleTime; } public void setMaxIdleTime(int maxIdleTime) { this.maxIdleTime = maxIdleTime; } public String getTestQuery() { return testQuery; } public void setTestQuery(String testQuery) { this.testQuery = testQuery; } }
package com.hongmoshui.test.datasource.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mysql.datasource.atomikos.test2") public class DBConfig2 { private String url; private String username; private String password; private int minPoolSize; private int maxPoolSize; private int maxLifetime; private int borrowConnectionTimeout; private int loginTimeout; private int maintenanceInterval; private int maxIdleTime; private String testQuery; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } 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 int getMinPoolSize() { return minPoolSize; } public void setMinPoolSize(int minPoolSize) { this.minPoolSize = minPoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public int getMaxLifetime() { return maxLifetime; } public void setMaxLifetime(int maxLifetime) { this.maxLifetime = maxLifetime; } public int getBorrowConnectionTimeout() { return borrowConnectionTimeout; } public void setBorrowConnectionTimeout(int borrowConnectionTimeout) { this.borrowConnectionTimeout = borrowConnectionTimeout; } public int getLoginTimeout() { return loginTimeout; } public void setLoginTimeout(int loginTimeout) { this.loginTimeout = loginTimeout; } public int getMaintenanceInterval() { return maintenanceInterval; } public void setMaintenanceInterval(int maintenanceInterval) { this.maintenanceInterval = maintenanceInterval; } public int getMaxIdleTime() { return maxIdleTime; } public void setMaxIdleTime(int maxIdleTime) { this.maxIdleTime = maxIdleTime; } public String getTestQuery() { return testQuery; } public void setTestQuery(String testQuery) { this.testQuery = testQuery; } }
package com.hongmoshui.test.datasource; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.hongmoshui.test.datasource.config.DBConfig1; import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; @Configuration // basePackages 最好分开配置 如果放在同一个文件夹可能会报错 @MapperScan(basePackages = "com.hongmoshui.test.datasource.user.user1", sqlSessionTemplateRef = "testSqlSessionTemplate") public class TestMyBatisConfig1 { // 配置数据源 @Primary @Bean(name = "testDataSource") public DataSource testDataSource(DBConfig1 testConfig) throws SQLException { MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); mysqlXaDataSource.setUrl(testConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(testConfig.getPassword()); mysqlXaDataSource.setUser(testConfig.getUsername()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName("testDataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(testConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(testConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime()); xaDataSource.setTestQuery(testConfig.getTestQuery()); return xaDataSource; } @Primary @Bean(name = "testSqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Primary @Bean(name = "testSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
package com.hongmoshui.test.datasource; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.hongmoshui.test.datasource.config.DBConfig1; import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; @Configuration // basePackages 最好分开配置 如果放在同一个文件夹可能会报错 @MapperScan(basePackages = "com.hongmoshui.test.datasource.user.user1", sqlSessionTemplateRef = "test2SqlSessionTemplate") public class TestMyBatisConfig2 { // 配置数据源 @Bean(name = "test2DataSource") public DataSource testDataSource(DBConfig1 testConfig) throws SQLException { MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); mysqlXaDataSource.setUrl(testConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(testConfig.getPassword()); mysqlXaDataSource.setUser(testConfig.getUsername()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName("test2DataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(testConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(testConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime()); xaDataSource.setTestQuery(testConfig.getTestQuery()); return xaDataSource; } @Bean(name = "test2SqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "test2SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
@EnableConfigurationProperties(value = { DBConfig1.class, DBConfig2.class })
#log4j.rootLogger=CONSOLE,info,error,DEBUG log4j.rootLogger=info,error,CONSOLE,DEBUG log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.logger.info=info log4j.appender.info=org.apache.log4j.DailyRollingFileAppender log4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.info.datePattern=‘.‘yyyy-MM-dd log4j.appender.info.Threshold = info log4j.appender.info.append=true #log4j.appender.info.File=/home/admin/pms-api-services/logs/info/api_services_info log4j.appender.info.File=D:/testlogspace/pms-api-services/logs/info/api_services_info log4j.logger.error=error log4j.appender.error=org.apache.log4j.DailyRollingFileAppender log4j.appender.error.layout=org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.error.datePattern=‘.‘yyyy-MM-dd log4j.appender.error.Threshold = error log4j.appender.error.append=true #log4j.appender.error.File=/home/admin/pms-api-services/logs/error/api_services_error log4j.appender.error.File=D:/testlogspace/pms-api-services/logs/error/api_services_error log4j.logger.DEBUG=DEBUG log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.DEBUG.datePattern=‘.‘yyyy-MM-dd log4j.appender.DEBUG.Threshold = DEBUG log4j.appender.DEBUG.append=true #log4j.appender.DEBUG.File=/home/admin/pms-api-services/logs/debug/api_services_debug log4j.appender.DEBUG.File=D:/testlogspace/pms-api-services/logs/debug/api_services_debug
代码引入中使用【import org.apache.log4j.Logger】:
private static Logger log = Logger.getLogger(TestController.class);
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
package com.hongmoshui.test.datasource.aop; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Aspect @Component public class WebLogAspect { private Logger logger = Logger.getLogger(getClass()); @Pointcut("execution(public * com.hongmoshui.test.datasource.controller..*.*(..))") public void webLog() { } @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String name = (String) enu.nextElement(); logger.info(String.format("name:{},value:{}", name, request.getParameter(name))); } } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 处理完请求,返回内容 logger.info("RESPONSE : " + ret); } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <diskStore path="java.io.tmpdir/Tmp_EhCache" /> <!-- 默认配置 --> <defaultCache maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LRU" overflowToDisk="false" /> <cache name="baseCache" maxElementsInMemory="10000" maxElementsOnDisk="100000" /> </ehcache> <!--1.配置的相关信息介绍 2.name:缓存名称。 3.maxElementsInMemory:缓存最大个数。 4.eternal:对象是否永久有效,一但设置了,timeout将不起作用。 5.timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 6.timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 7.overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 8.diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 9.maxElementsOnDisk:硬盘最大缓存个数。 10.diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. 11.diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 12.memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 13.clearOnFlush:内存数量最大时是否清除。 14.-->
package com.hongmoshui.test.datasource.user.user1; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import com.hongmoshui.test.datasource.entity.User; @CacheConfig(cacheNames = "baseCache") public interface User1Mapper { @Insert("insert into users values(null,#{name},#{age});") public int addUser(@Param("name") String name, @Param("age") Integer age); @Cacheable @Select("select * from users where name=#{name};") public User queryUser(String name); }
@Autowired private CacheManager cacheManager; @RequestMapping("/remoKey") public void remoKey() { cacheManager.getCache("baseCache").clear(); }
在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置
package com.hongmoshui.test.datasource; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); } }
启动加上@EnableAsync ,需要执行异步方法上加入 @Async
配置文件值
name=hongmoshui.com
后台代码:
@Value("${name}") private String name; @ResponseBody @RequestMapping("/getValue") public String getValue() { return name; }
spring.profiles.active=pre
注:
application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
server.port=8888
server.context-path=/hongmoshui
创建application.yml
server: port: 8090 context-path: /hongmoshui
使用mvn package 打包
使用java –jar 包名
如果报错没有主清单,在pom文件中新增
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <maimClass>com.hongmoshui.app.App</maimClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
标签:gem live 实现 mvc path round web页面 修改端口号 char
原文地址:https://www.cnblogs.com/hongmoshui/p/10990330.html