Spring Boot 中,random.* 随机值

在 Spring Boot 中,random.* 相关的属性确实有一定的范围,但主要包括以下几种类型:

random.int: 生成一个随机整数。
random.long: 生成一个随机长整数。
random.uuid: 生成一个随机 UUID(通用唯一标识符)。
random.boolean: 生成一个随机布尔值 (true 或 false)。
random.alphanumeric: 生成一个指定长度的随机字母数字字符串。
random.pseudopassword: 生成一个伪密码,通常用于模拟密码场景。

  1. random.int
    配置:

在 application.properties 文件中:

properties
random.int=1000

在 application.yml 文件中:

yaml

random:
  int: 1000

说明: 生成一个 0 到 1000 之间的随机整数。这个属性在配置文件中设置了一个范围的上限。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomIntComponent {

    @Value("${random.int}")
    private int randomInt;

    public void printRandomInt() {
        System.out.println("Random Integer: " + randomInt);
    }
}
  1. random.long
    配置:

在 application.properties 文件中:

properties
random.long=10000000000

在 application.yml 文件中:

yaml

random:
  long: 10000000000

说明: 生成一个 0 到 10000000000 之间的随机长整数。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomLongComponent {

    @Value("${random.long}")
    private long randomLong;

    public void printRandomLong() {
        System.out.println("Random Long: " + randomLong);
    }
}
  1. random.uuid
    配置:

在 application.properties 文件中:

properties
random.uuid=true

在 application.yml 文件中:

yaml

random:
  uuid: true

说明: 生成一个随机 UUID(通用唯一标识符)。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomUuidComponent {

    @Value("${random.uuid}")
    private String randomUuid;

    public void printRandomUuid() {
        System.out.println("Random UUID: " + randomUuid);
    }
}
  1. random.boolean
    配置:

在 application.properties 文件中:

properties
random.boolean=true

在 application.yml 文件中:

yaml

random:
  boolean: true

说明: 生成一个随机布尔值 (true 或 false)。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomBooleanComponent {

    @Value("${random.boolean}")
    private boolean randomBoolean;

    public void printRandomBoolean() {
        System.out.println("Random Boolean: " + randomBoolean);
    }
}
  1. random.alphanumeric
    配置:

在 application.properties 文件中:

properties

random.alphanumeric=8

在 application.yml 文件中:

yaml

random:
  alphanumeric: 8

说明: 生成一个长度为 8 的随机字母数字字符串。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomAlphanumericComponent {

    @Value("${random.alphanumeric}")
    private String randomAlphanumeric;

    public void printRandomAlphanumeric() {
        System.out.println("Random Alphanumeric: " + randomAlphanumeric);
    }
}
  1. random.pseudopassword
    配置:

在 application.properties 文件中:

properties

random.pseudopassword=12

在 application.yml 文件中:

yaml

random:
  pseudopassword: 12

说明: 生成一个长度为 12 的伪密码(通常是一个复杂的随机字符串)。

在代码中使用:

java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RandomPseudopasswordComponent {

    @Value("${random.pseudopassword}")
    private String randomPseudopassword;

    public void printRandomPseudopassword() {
        System.out.println("Random Pseudopassword: " + randomPseudopassword);
    }
}
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@48c5a07d testClass = jp.co.sej.ssc.sh.ssha0070.logic.impl.Ssha0070LogicTest17, locations = [], classes = [jp.co.sej.ssc.Application], contextInitializerClasses = [], activeProfiles = ["test"], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true", "server.port=0"], contextCustomizers = [org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@1ad926d3, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@28782602, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5339bbad, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@221efc42, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5649ec46, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@2228db21, org.springframework.boot.test.context.SpringBootTestAnnotation@c9bfde14], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null] at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:180) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130) at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:122) at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:106) at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:63) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260) at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:163) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) at java.base/java.util.Optional.orElseGet(Optional.java:364) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) Caused by: org.springframework.context.ApplicationContextException: Unable to start web server at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:165) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:619) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1463) at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:553) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152) ... 18 more Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:147) at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:107) at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:516) at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:222) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:188) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:162) ... 32 more Caused by: java.lang.IllegalStateException: StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[] failed to start at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.rethrowDeferredStartupExceptions(TomcatWebServer.java:209) at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:131) ... 37 more
最新发布
11-13
WebMergedContextConfiguration@355c94be testClass = com.example.dietsportmanage.GenerateApplicationTests, locations = [], classes = [com.example.DietsportmanageApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@2fba3fc4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1c852c0f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@6b58b9e9, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@2b9ed6da, org.springframework.boot.test.autoconfigure.OnFailureConditionReportContextCustomizerFactory$OnFailureConditionReportContextCustomizer@421e361, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@7ef27d7f, org.springframework.test.context.support.DynamicPropertiesContextCustomizer@0, org.springframework.boot.test.context.SpringBootTestAnnotation@992bef3a], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
04-01
`org.springframework.boot.env.EnvironmentPostProcessor` 是 Spring Boot 提供的一个接口,用于在 Spring Boot 应用启动时对环境配置进行后置处理。 ### 使用场景 - **系统环境变量集成**:在 Spring Boot 应用启动时,将系统环境变量注册为 Spring Environment 的属性源,使其可通过 `@Value` 或 `Environment` 接口直接访问。例如 `SystemEnvironmentPropertySourceEnvironmentPostProcessor` 类,能自动将操作系统的环境变量转换为 Spring 的属性键对,像环境变量 `SPRING_PORT=8080` 可通过 `@Value("${spring.port}")` 获取 [^1]。 - **动态属性生成**:在应用启动时动态生成一些属性并注册到环境中。如 `RandomValuePropertySource` 类,能在 Spring Boot 应用启动时动态生成随机(如字符串、数等),并将其注册为 `Environment` 的属性源,供应用通过标准属性占位符(如 `${random.value}`)访问 [^3]。 ### 使用方法 要使用 `EnvironmentPostProcessor`,需要创建一个实现该接口的类,并实现 `postProcessEnvironment` 方法。以下是一个简单的示例: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment; public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { // 在这里可以对 environment 进行自定义处理 // 例如添加自定义的属性源 // environment.getPropertySources().addFirst(new MyCustomPropertySource()); } } ``` 还需要在 `src/main/resources/META-INF/spring.factories` 文件中配置该处理器: ```properties org.springframework.boot.env.EnvironmentPostProcessor=com.example.CustomEnvironmentPostProcessor ``` 这样,Spring Boot 启动时会自动加载并调用 `CustomEnvironmentPostProcessor` 的 `postProcessEnvironment` 方法 [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值