开发者社区 问答 正文

如何使用Spring Boot注释外部化线程中的值

我试图从将Thread扩展到configuration.properties的类中外部化一些值,但是这些值未更新,这是我使用的示例:

@Component
@Scope("prototype")
public @interface ScheduledJob {..}

@configuration
@PropertySource("classpath:application.properties")
public class Classname extends Thread {  
     @Autowired
     @Value("${sleep.sampling.s}")
     private static int sleep;
 }

@SpringBootApplication
public class  Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
}

你能帮忙吗?

展开
收起
几许相思几点泪 2019-12-08 21:51:21 387 分享 版权
阿里云 AI 助理回答

在Spring框架中,使用@Value注解注入属性值到静态字段是不被支持的。@Value主要用于实例字段的注入,而静态字段在Spring容器初始化时可能还未完成依赖注入。为了实现你的需求,你可以采用以下几种方式:

1. 使用@PostConstruct方法初始化静态变量

虽然直接注入到静态字段不可行,但你可以在类初始化后通过一个非静态的@PostConstruct方法来设置静态变量的值。

@Component
public class Classname extends Thread {

    private static int sleep;

    @Value("${sleep.sampling.s}")
    private int sleepInstance;

    @PostConstruct
    public void init() {
        Classname.sleep = this.sleepInstance;
    }
}

2. 使用Environment获取配置

另一种方法是通过注入Environment接口来获取配置属性。

@Component
public class Classname extends Thread {

    private static int sleep;

    @Autowired
    private Environment env;

    @PostConstruct
    public void init() {
        sleep = Integer.parseInt(env.getProperty("sleep.sampling.s"));
    }
}

3. 自定义配置类

创建一个配置类,专门用于持有这些配置属性,并以非静态的方式注入,然后在需要的地方引用这个配置类的实例。

@ConfigurationProperties(prefix = "sleep")
public class SleepConfig {
    private int samplingS;

    // getters and setters
}

@Configuration
@EnableConfigurationProperties(SleepConfig.class)
public class AppConfig {
    // ...
}

@Component
public class Classname extends Thread {

    @Autowired
    private SleepConfig sleepConfig;

    private int sleep;

    @PostConstruct
    public void init() {
        sleep = sleepConfig.getSamplingS();
    }
}

注意事项

  • 确保application.properties文件的位置正确,并且Spring Boot能够找到它。
  • 如果你正在使用Spring Boot,确保添加了对spring-boot-starter-configuration-processor的依赖(如果使用了@ConfigurationProperties)以便于IDE识别配置属性。
  • 检查是否有拼写错误或路径问题导致配置无法加载。

以上方法应该能帮助你成功地从配置文件外部化并读取属性值。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答