Skip to content

Commit 5488494

Browse files
committed
阅读Spring Boot手册,演示更多功能
1 parent 163b6d9 commit 5488494

File tree

18 files changed

+111
-39
lines changed

18 files changed

+111
-39
lines changed

examples/boot-api/src/main/java/org/springside/examples/bootapi/BootApiApplication.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public class BootApiApplication {
1515
* 1. 扫描当前package下的class设置自动注入的Bean<br/>
1616
* 2. 也支持用@Bean标注的类配置Bean <br/>
1717
* 3. 根据classpath中的三方包Class及集中的application.properties条件配置三方包,如线程池 <br/>
18-
* 4. 也支持用@Configuration标注的类配置三方包,如线程池,Servlet.
18+
* 4. 也支持用@Configuration标注的类配置三方包.
1919
*/
2020
public static void main(String[] args) throws Exception {
2121
SpringApplication.run(BootApiApplication.class, args);

examples/boot-api/src/main/java/org/springside/examples/bootapi/config/H2ConsoleStarter.java

+3-8
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,22 @@
44
import javax.servlet.ServletException;
55
import javax.servlet.ServletRegistration;
66

7-
import org.springframework.beans.factory.annotation.Autowired;
87
import org.springframework.boot.context.embedded.ServletContextInitializer;
98
import org.springframework.context.annotation.Configuration;
10-
import org.springframework.core.env.Environment;
9+
import org.springframework.context.annotation.Profile;
1110

1211
/**
1312
* 在非生产环境里,初始化H2Console管理嵌入式H2.
1413
*
1514
* @author calvin
1615
*/
1716
@Configuration
17+
@Profile(Profiles.NOT_PRODUCTION)
1818
public class H2ConsoleStarter implements ServletContextInitializer {
1919

20-
@Autowired
21-
private Environment env;
22-
2320
@Override
2421
public void onStartup(ServletContext servletContext) throws ServletException {
25-
if (!env.acceptsProfiles(Profiles.PRODUCTION)) {
26-
initH2Console(servletContext);
27-
}
22+
initH2Console(servletContext);
2823
}
2924

3025
private void initH2Console(ServletContext servletContext) {

examples/boot-api/src/main/java/org/springside/examples/bootapi/config/Profiles.java

+5-1
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,9 @@
77
*/
88
public class Profiles {
99

10-
public static final String PRODUCTION = "production";
10+
public static final String PRODUCTION = "prod";
11+
public static final String NOT_PRODUCTION = "!prod";
12+
13+
public static final String QA = "qa";
14+
public static final String DEVELOPMENT = "dev";
1115
}

examples/boot-api/src/main/java/org/springside/examples/bootapi/service/AccountService.java

+24-8
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22

33
import java.util.concurrent.TimeUnit;
44

5+
import javax.annotation.PostConstruct;
6+
57
import org.slf4j.Logger;
68
import org.slf4j.LoggerFactory;
79
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.beans.factory.annotation.Value;
11+
import org.springframework.boot.actuate.metrics.CounterService;
812
import org.springframework.http.HttpStatus;
913
import org.springframework.stereotype.Service;
1014
import org.springframework.transaction.annotation.Transactional;
@@ -24,12 +28,26 @@ public class AccountService {
2428

2529
private static Logger logger = LoggerFactory.getLogger(AccountService.class);
2630

27-
private Cache<String, Account> loginUsers = CacheBuilder.newBuilder().maximumSize(1000)
28-
.expireAfterAccess(10, TimeUnit.MINUTES).build();
29-
3031
@Autowired
3132
private AccountDao accountDao;
3233

34+
// 注入配置值
35+
@Value("${app.loginTimeoutSecs}")
36+
private int loginTimeoutSecs;
37+
38+
// codehale metrics
39+
@Autowired
40+
private CounterService counterService;
41+
42+
// guava cache
43+
private Cache<String, Account> loginUsers;
44+
45+
@PostConstruct
46+
public void init() {
47+
loginUsers = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(loginTimeoutSecs, TimeUnit.SECONDS)
48+
.build();
49+
}
50+
3351
@Transactional(readOnly = true)
3452
public String login(String email, String password) {
3553
Account account = accountDao.findByEmail(email);
@@ -44,6 +62,7 @@ public String login(String email, String password) {
4462

4563
String token = Identities.uuid2();
4664
loginUsers.put(token, account);
65+
counterService.increment("loginUser");
4766
return token;
4867
}
4968

@@ -53,6 +72,7 @@ public void logout(String token) {
5372
logger.error("logout an alreay logout token:" + token);
5473
} else {
5574
loginUsers.invalidate(token);
75+
counterService.decrement("loginUser");
5676
}
5777
}
5878

@@ -80,11 +100,7 @@ public void register(String email, String name, String password) {
80100
accountDao.save(account);
81101
}
82102

83-
private static String hashPassword(String password) {
103+
protected static String hashPassword(String password) {
84104
return Encodes.encodeBase64(Digests.sha1(password));
85105
}
86-
87-
public static void main(String[] args) throws Exception {
88-
System.out.println("hashPassword:" + hashPassword("springside"));
89-
}
90106
}

examples/boot-api/src/main/resources/application-production.properties examples/boot-api/src/main/resources/application-prod.properties

+7
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,10 @@ spring.datasource.initialize=false
1313
spring.datasource.max-idle=10
1414
spring.datasource.max-active=100
1515

16+
# logging
17+
logging.file=/var/log/boot-api.log
18+
logging.level.org.hibernate=WARN
19+
20+
# tomcat settings
21+
#server.contextPath=/
22+
#server.tomcat.maxThreads=200

examples/boot-api/src/main/resources/application.properties

+6-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
server.port=8080
33
management.port=7002
44

5+
#application
6+
app.loginTimeoutSecs=600
7+
8+
# other
59
spring.jackson.serialization.INDENT_OUTPUT=true
610
spring.datasource.sqlScriptEncoding=UTF-8
711

@@ -11,5 +15,5 @@ spring.jpa.hibernate.ddl-auto=none
1115
spring.jpa.showsql=false
1216

1317
# /info endpoint
14-
info.app.name=Spring Boot Web Service Example
15-
info.app.version=${project.version}
18+
info.app.name=Spring Boot WebService Example
19+
info.app.version=${project.version}

examples/boot-api/src/main/resources/schema.sql

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
drop table if exists book;
2+
drop table if exists account;
3+
drop table if exists message;
4+
5+
16
create table book (
27
id bigint generated by default as identity,
38
douban_id varchar(64) not null,

examples/boot-api/src/main/webapp/index.html

+2-3
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,10 @@
77

88
<p>Access below book endpoint:
99
<ul>
10-
<li><a href="http://localhost:8080/api/books?page=0&size=10">http://localhost:8080/api/books?page=0&size=10</a></li>
11-
<li><a href="http://localhost:8080/api/books?page=1&size=2">http://localhost:8080/api/books?page=1&size=2</a></li>
10+
<li><a href="http://localhost:8080/api/books?page=0&size=10">List first page books(page size=10)</a></li>
11+
<li><a href="http://localhost:8080/api/books?page=1&size=2">List second page books(page size=2)</a></li>
1212
</ul>
1313

14-
1514
<p>Access below management endpoint:</p>
1615
<ul>
1716
<li><a href="http://localhost:7002/health">http://localhost:7002/health</a></li>

examples/boot-api/src/test/java/org/springside/examples/bootapi/functional/BookEndpointTest.java

+3-6
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,15 @@
2222
import org.junit.Test;
2323
import org.junit.runner.RunWith;
2424
import org.springframework.beans.factory.annotation.Value;
25-
import org.springframework.boot.test.IntegrationTest;
2625
import org.springframework.boot.test.SpringApplicationConfiguration;
27-
import org.springframework.boot.test.TestRestTemplate;
26+
import org.springframework.boot.test.WebIntegrationTest;
2827
import org.springframework.http.HttpEntity;
2928
import org.springframework.http.HttpHeaders;
3029
import org.springframework.http.HttpMethod;
3130
import org.springframework.http.HttpStatus;
3231
import org.springframework.http.ResponseEntity;
3332
import org.springframework.test.annotation.DirtiesContext;
3433
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
35-
import org.springframework.test.context.web.WebAppConfiguration;
3634
import org.springframework.web.client.RestTemplate;
3735
import org.springside.examples.bootapi.BootApiApplication;
3836
import org.springside.examples.bootapi.dto.BookDto;
@@ -42,8 +40,7 @@
4240

4341
@RunWith(SpringJUnit4ClassRunner.class)
4442
@SpringApplicationConfiguration(classes = BootApiApplication.class)
45-
@WebAppConfiguration
46-
@IntegrationTest("server.port=0")
43+
@WebIntegrationTest("server.port=0")
4744
@DirtiesContext
4845
public class BookEndpointTest {
4946

@@ -57,7 +54,7 @@ public class BookEndpointTest {
5754

5855
@Before
5956
public void setup() {
60-
restTemplate = new TestRestTemplate();
57+
restTemplate = new RestTemplate();
6158
resourceUrl = "http://localhost:" + port + "/api/books";
6259
loginUrl = "http://localhost:" + port + "/api/accounts/login";
6360
logoutUrl = "http://localhost:" + port + "/api/accounts/logout";

examples/boot-api/src/test/java/org/springside/examples/bootapi/repository/BookDaoTest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ public class BookDaoTest {
2424

2525
@Test
2626
public void findByUserId() {
27-
List<Book> books = bookDao.findByOwnerId(1L, new PageRequest(1, 10));
28-
assertThat(books).hasSize(1);
27+
List<Book> books = bookDao.findByOwnerId(1L, new PageRequest(0, 10));
28+
assertThat(books).hasSize(2);
2929
assertThat(books.get(0).title).isEqualTo("Big Data日知录");
3030
}
3131
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package org.springside.examples.bootapi.service;
2+
3+
import org.junit.Test;
4+
5+
public class AccountServiceTest {
6+
7+
@Test
8+
public void hash() throws Exception {
9+
System.out.println("hashPassword:" + AccountService.hashPassword("springside"));
10+
}
11+
12+
}

examples/boot-api/start.sh

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/bin/bash
2+
3+
java -Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom -jar target/boot-api-5.0.0-SNAPSHOT.war --spring.profiles.active=prod
4+
5+
#set the server port
6+
#java -Xmx1024m -jar target/boot-api-5.0.0-SNAPSHOT.war --server.port=9090
7+
8+
#set the properties file location
9+
#java -Xmx1024m -jar target/boot-api-5.0.0-SNAPSHOT.war --spring.config.location=/var/myapp/conf

examples/boot-showcase/README.txt

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ What is more?
44

55
* 不把Spring boot的pom.xml作为parent
66
* 自定义Logback输出格式
7-
* 自定义Jackson输出格式
87
* 禁止无用的SpringBoot Endpoint
98
* 使用JavaSimon, 演示自定义 AOP切面与Servlet映射
109

examples/boot-showcase/src/main/java/org/springside/examples/showcase/common/JavaSimonConfig.java examples/boot-showcase/src/main/java/org/springside/examples/showcase/config/JavaSimonConfig.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package org.springside.examples.showcase.common;
1+
package org.springside.examples.showcase.config;
22

33
import org.javasimon.console.SimonConsoleServlet;
44
import org.javasimon.spring.MonitoredMeasuringPointcut;

examples/boot-showcase/src/main/resources/application-production.properties examples/boot-showcase/src/main/resources/application-prod.properties

+11
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,14 @@ spring.datasource.initialize=false
1010
spring.datasource.max-idle=10
1111
spring.datasource.max-active=100
1212

13+
# logging
14+
logging.file=/var/log/boot-showcase.log
15+
logging.level.org.hibernate=WARN
16+
17+
# tomcat settings
18+
#server.contextPath
19+
#server.tomcat.maxThreads
20+
#server.address
21+
#server.sessiontimeout
22+
23+

examples/boot-showcase/src/main/resources/application.properties

-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
server.port=8080
33
management.port=7002
44

5-
# logging
6-
logging.file=/tmp/logs/boot-showcase.log
7-
85
# other
96
spring.datasource.sqlScriptEncoding=UTF-8
107
http.mappers.json-pretty-print=true

quick-start.bat

+7-1
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,20 @@ echo [Pre-Requirement] Makesure install JDK 7.0+ and set the JAVA_HOME.
33
echo [Pre-Requirement] Makesure install Maven 3.0.3+ and set the PATH.
44

55
set MVN=mvn
6-
set MAVEN_OPTS=%MAVEN_OPTS% -XX:MaxPermSize=128m
6+
set MAVEN_OPTS=%MAVEN_OPTS% -XX:MaxPermSize=128M
77

88
echo [Step 1] Install all springside modules to local maven repository.
99
cd modules
1010
call %MVN% clean install
1111
if errorlevel 1 goto error
1212

1313

14+
echo [Step 2] run boot-api project.
15+
cd ..\examples\boot-api
16+
call %MVN% spring-boot:run
17+
if errorlevel 1 goto error
18+
19+
1420
goto end
1521
:error
1622
echo Error Happen!!

quick-start.sh

+13-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,19 @@
33
echo "[Pre-Requirement] Makesure install JDK 7.0+ and set the JAVA_HOME."
44
echo "[Pre-Requirement] Makesure install Maven 3.0.3+ and set the PATH."
55

6-
set MAVEN_OPTS=$MAVEN_OPTS -XX:MaxPermSize=128m
6+
export MAVEN_OPTS="$MAVEN_OPTS -Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom"
77

88
echo "[Step 1] Install all springside modules to local maven repository."
99
cd modules
10-
mvn clean install
10+
mvn clean install
11+
if [ $? -ne 0 ];then
12+
echo "Quit because maven install fail"
13+
exit -1
14+
fi
15+
16+
echo "[Step 2] run boot-api project."
17+
cd ../examples/boot-api
18+
mvn spring-boot:run
19+
20+
21+

0 commit comments

Comments
 (0)