

五个实用的 Spring Boot 小技巧,提升你的开发效率


1. 在 Spring Boot 启动时执行初始化逻辑

背景




解决方案




实现步骤


使用 CommandLineRunner 接口
4jpublic class DatabaseInitializer implements CommandLineRunner {public void run(String... args) {// 这里编写初始化逻辑,例如更新数据库字段log.info("执行数据库初始化操作...");}}
使用 ApplicationRunner 接口
4jpublic class DatabaseInitializer implements ApplicationRunner {public void run(ApplicationArguments args) {// 这里编写初始化逻辑,例如更新数据库字段log.info("执行数据库初始化操作...");}}
监听应用上下文刷新事件
4jpublic class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {public void onApplicationEvent(ContextRefreshedEvent event) {// 这里编写初始化逻辑,例如更新数据库字段log.info("执行数据库初始化操作...");}}


确保初始化逻辑只执行一次


if (!dictionaryService.isInitialized()) {// 执行初始化操作dictionaryService.initialize();dictionaryService.setInitialized(true);}


2. 动态控制数据源的加载

背景




实现方法


1. 禁用 Spring Boot 的数据源自动配置
在启动类上添加以下注解,排除默认的数据源自动配置:
(exclude = { DataSourceAutoConfiguration.class })public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
2. 创建自定义的数据源配置类
使用 @ConditionalOnProperty 注解,根据配置文件中的属性决定是否加载数据源:
(name = "spring.datasource.enabled", havingValue = "true")public class DataSourceConfig {public DataSource dataSource() {// 配置数据源,例如 HikariDataSourceHikariDataSource dataSource = new HikariDataSource();dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");dataSource.setUsername("root");dataSource.setPassword("password");return dataSource;}}
3. 调整仓库类的依赖注入
对于需要注入数据源的仓库类,使用 @Autowired(required = false),确保在数据源未加载时不会导致应用启动失败:
public class MyRepository {(required = false)private JdbcTemplate jdbcTemplate;// 使用 jdbcTemplate 执行数据库操作}
4. 在配置文件中控制数据源的启用状态
spring:datasource:enabled: true # 设置为 false 时,数据源不会被加载


3. 根据不同环境加载配置文件

背景




实现方法

使用 Spring Profiles

Spring 提供了 Profiles 功能,可以根据激活的环境配置不同的属性。
1. 创建不同环境的配置文件
application-dev.yml(开发环境)
application-test.yml(测试环境)
application-prod.yml(生产环境)
每个文件中包含对应环境的配置:
# application-dev.ymlspring:datasource:url: jdbc:mysql://localhost:3306/devdbusername: devuserpassword: devpass
# application-test.ymlspring:datasource:url: jdbc:mysql://localhost:3306/testdbusername: testuserpassword: testpass
# application-prod.ymlspring:datasource:url: jdbc:mysql://localhost:3306/proddbusername: produserpassword: prodpass
2. 在启动时指定激活的 Profile
通过命令行参数指定要激活的环境:
java -jar yourapp.jar --spring.profiles.active=devapplication.yml 中默认指定:spring:profiles:active: dev

使用 Nacos 进行配置管理

结合 Nacos 等配置中心,可以更灵活地管理不同环境的配置:
spring:profiles: devcloud:nacos:discovery:: 127.0.0.1:8848config:: ${spring.cloud.nacos.discovery.server-addr}:data-id: database-dev.yamlgroup: DEFAULT_GROUPrefresh: truedata-id: redis-dev.yamlgroup: DEFAULT_GROUPrefresh: true




4. 配置文件加密,保障敏感信息安全

背景




实现步骤

引入 Jasypt 依赖

在 pom.xml 中添加 Jasypt 的 Spring Boot 启动器依赖:
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.4</version></dependency>
注意:确保使用最新版本,以获得最佳的安全性和功能支持。

配置加密器

在 application.yml 中配置加密器的密码和算法:
jasypt:encryptor:password: your-encryption-password # 加密密钥,建议通过环境变量传递algorithm: PBEWithMD5AndDES
安全提示:为了防止加密密钥泄露,建议将 jasypt.encryptor.password 设置为环境变量或通过启动参数传递,而不是直接写在配置文件中。

加密敏感信息

编写一个测试用例,使用 Jasypt 加密敏感信息:
public class EncryptTest {private StringEncryptor encryptor;public void encryptProperties() {String url = encryptor.encrypt("jdbc:mysql://localhost:3306/mydb");String username = encryptor.encrypt("root");String password = encryptor.encrypt("password123");System.out.println("Encrypted URL: " + url);System.out.println("Encrypted Username: " + username);System.out.println("Encrypted Password: " + password);}}
运行测试后,将输出加密后的字符串,将其替换到 application.yml 中对应的位置:
spring:datasource:url: ENC(encrypted-url-string)username: ENC(encrypted-username-string)password: ENC(encrypted-password-string)

启动时传递加密密钥

使用环境变量
export JASYPT_ENCRYPTOR_PASSWORD=your-encryption-password使用启动参数
java -jar yourapp.jar --jasypt.encryptor.password=your-encryption-password

5. 精简打包后的 JAR 文件,提升部署效率

背景




解决方案




实现步骤


配置 Maven 插件
<build><plugins><!-- Spring Boot Maven 插件 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><executable>true</executable><layout>ZIP</layout><!-- 指定需要内置的依赖,未列出的依赖将外置 --><includes><include><groupId>com.example</groupId><artifactId>common-library</artifactId></include></includes></configuration></plugin><!-- Maven 依赖插件,用于复制依赖到外部目录 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId><version>3.1.2</version><executions><execution><id>copy-dependencies</id><phase>package</phase><goals><goal>copy-dependencies</goal></goals><configuration><outputDirectory>${project.build.directory}/lib</outputDirectory><includeScope>runtime</includeScope></configuration></execution></executions></plugin></plugins></build>
打包项目
mvn clean package启动应用时指定外部依赖路径
java -Dloader.path=./lib -jar yourapp.jar

优点


节省带宽:
加快部署:
灵活管理依赖:


注意事项


依赖稳定性:
服务器配置:


总结

以上五个 Spring Boot 的实用小技巧,涵盖了应用初始化、数据源管理、环境配置、配置安全以及打包优化等方面。合理运用这些技巧,能够显著提升开发效率、增强应用的安全性,并优化部署流程。希望这些内容对你在 Spring Boot 项目中的开发有所帮助!




原文作者:IT枫斗者;如有侵权,请联系管理员删除。