为了创建一个Spring Boot的演示项目,您需要遵循以下步骤:
- 设置项目:
使用Spring Initializr或STS (Spring Tool Suite) 来初始化一个新的Spring Boot项目。选择以下依赖:- Spring Boot Web
- Spring Boot Starter Data JPA (如果你打算使用JPA)
- Spring Boot Starter DevTools (为了开发时自动重新加载)
- 创建主应用类:
在src/main/java
目录下,创建一个名为DemoApplication
的类,并使其成为Spring Boot的主类。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 配置文件:
在src/main/resources
目录下,创建或修改application.properties
文件,以配置数据库连接和其他设置。例如:
spring.datasource.url=jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=rootpassword
spring.jpa.hibernate.ddl-auto=update
- 日志配置:
在src/main/resources
目录下,找到logback-spring.xml
或logback.xml
,然后添加日志配置。例如:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>
- 创建Controller:
在src/main/java/com/example/demo
目录下,创建一个新的Java类,例如DemoController
。在该类中,您可以创建简单的RESTful端点。例如:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
- 运行应用:
启动您的应用并访问http://localhost:8080/hello
,您应该看到"Hello, Spring Boot!"的响应。7. 添加业务逻辑:
根据您的需求,可以在DemoController
中添加更多的端点,或者创建一个新的服务类来处理业务逻辑。例如,创建一个UserService
类来处理与用户相关的逻辑。
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getUserInfo(String username) {
// 实现获取用户信息的逻辑
return "User Info for " + username;
}
}
然后在DemoController
中注入这个服务并使用它:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
private final UserService userService;
@Autowired
public DemoController(UserService userService) {
this.userService = userService;
}
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
@GetMapping("/user")
public String getUserInfo(@RequestParam String username) {
return userService.getUserInfo(username);
}
}
- 数据库交互:
如果您打算使用数据库,可以创建一个DAO (Data Access Object) 来处理数据库交互。例如,创建一个UserDao
类来处理与用户表相关的数据库操作。使用JPA (Java Persistence API) 来简化数据库操作。 - 安全性:
考虑应用的安全性,使用Spring Security来添加认证和授权功能。您可以在pom.xml
中添加Spring Security的依赖,然后配置安全设置。 - 单元测试和集成测试:
编写单元测试和集成测试以确保代码的正确性。使用JUnit和Spring Boot Test框架来简化测试编写。 - 持续集成和持续部署 (CI/CD):
考虑使用CI/CD工具,如Jenkins或Travis CI,来自动化构建、测试和部署过程。这样可以使部署过程更加可靠和快速。
common-logging和log4j
Apache为了让众多的日志工具有一个相同操作方式,实现了一个通用日志工具包:commons-logging。而Log4j基本上是Java平台上最好的日志组件了。使用ommons-logging的Log接口,并由commons-logging在运行时决定使用哪种日志架构。现在,Apache通用日志工具commons-logging和Log4j已经成为Java日志的标准工具。
日志级别
- fatal:非常严重的错误,导致系统中止。期望这类信息能立即显示在状态控制台上。
- error:其它运行期错误或不是预期的条件。期望这类信息能立即显示在状态控制台上。
- warn:使用了不赞成使用的API、非常拙劣使用API, ‘几乎就是’错误。
- info:运行时产生的有意义的事件。期望这类信息能立即显示在状态控制台上。
- debug:系统流程中的细节信息。期望这类信息仅被写入log文件中。
- trace:更加细节的信息。期望这类信息仅被写入log文件中。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@SpringBootApplication
public class DemoLogTestApplication {
private static Log logger = LogFactory.getLog(DemoLogTestApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoLogTestApplication.class, args);
logger.trace("programb!");
logger.debug("programb!");
logger.info("programb!");
logger.warn("programb!");
logger.error("programb!");
logger.fatal("programb!");
}
}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-04 13:35:36.050 INFO 14504 --- [ main] com.example.demo.DemoLogTestApplication : Starting DemoLogTestApplication on PC-202008012041 with PID 14504 (G:\eclipse-workspace-Jee\demo-LogTest\target\classes started by Administrator in G:\eclipse-workspace-Jee\demo-LogTest)
2020-08-04 13:35:36.052 INFO 14504 --- [ main] com.example.demo.DemoLogTestApplication : No active profile set, falling back to default profiles: default
2020-08-04 13:35:36.677 INFO 14504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-04 13:35:36.683 INFO 14504 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-04 13:35:36.683 INFO 14504 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-04 13:35:36.684 INFO 14504 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded Apache Tomcat Native library [1.2.24] using APR version [1.7.0].
2020-08-04 13:35:36.684 INFO 14504 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2020-08-04 13:35:36.684 INFO 14504 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2020-08-04 13:35:36.689 INFO 14504 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1g 21 Apr 2020]
2020-08-04 13:35:36.762 INFO 14504 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-04 13:35:36.762 INFO 14504 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 676 ms
2020-08-04 13:35:36.902 INFO 14504 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-04 13:35:37.037 INFO 14504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-04 13:35:37.044 INFO 14504 --- [ main] com.example.demo.DemoLogTestApplication : Started DemoLogTestApplication in 1.249 seconds (JVM running for 2.601)
2020-08-04 13:35:37.047 INFO 14504 --- [ main] com.example.demo.DemoLogTestApplication : programb!
2020-08-04 13:35:37.047 WARN 14504 --- [ main] com.example.demo.DemoLogTestApplication : programb!
2020-08-04 13:35:37.047 ERROR 14504 --- [ main] com.example.demo.DemoLogTestApplication : programb!
2020-08-04 13:35:37.047 ERROR 14504 --- [ main] com.example.demo.DemoLogTestApplication : programb!