Java Spring将属性文件中的值读取到@SpringBootApplication类中
我有一个SpringBoot应用程序,我想从属性文件中读取一个值 我的@SpringBootApplication类是:Java Spring将属性文件中的值读取到@SpringBootApplication类中,java,spring,spring-boot,properties-file,Java,Spring,Spring Boot,Properties File,我有一个SpringBoot应用程序,我想从属性文件中读取一个值 我的@SpringBootApplication类是: @SpringBootApplication @ComponentScan(basePackages = "it.test") @PropertySource("classpath:application.properties") public class Application { private static Logger log = LogManager.g
@SpringBootApplication
@ComponentScan(basePackages = "it.test")
@PropertySource("classpath:application.properties")
public class Application {
private static Logger log = LogManager.getLogger();
@Value("${server.modem.delay}")
private int modemSmsDelay;
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean(initMethod = "start", destroyMethod = "stop")
public Service smsService() {
settings();
Service service = Service.getInstance();
return service;
}
private void settings() {
log.debug("Delay per invio sms " + modemSmsDelay +"ms");
Settings.gatewayDispatcherYield = modemSmsDelay;
}
}
不幸的是,在名为“设置”的方法中,如果在我的application.properties文件中,属性modemsmssdelay的值为1000,则该值也为0
在我的应用程序的其他部分,我可以毫无问题地读取值
==更新=====
我解决了这个问题。事实上,我的代码是有效的,不需要@PostConstruct来让@Value标记工作,如果它在一些情况下是必需的话。
我的Spring配置中有一个问题,它阻止了所有注释的执行,如@PostConstruct、@Autowire等等。
我从Spring打印警告消息的日志中注意到了这一点。尝试将@PostConstruct注释放在settings()方法上,而不是从构造函数调用它。这将导致在构造函数退出后自动调用该方法。这对我很有用: @资源私人环境强>
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import my.beautiful.code.SomeClient;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Resource
private Environment environment;
@Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Bean(name = "someClient")
public SomeClient loadSomeClient() {
SomeClient bean = new SomeClient();
...
bean.setHeaderContentType(environment.getProperty("contentType"));
bean.setRestUrl(environment.getProperty("rest.url"));
...
return bean;
}
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
在我的application.properties中
contentType=some_value
rest.url=http://localhost/....
HTH您不需要添加ComponentScan或PropertySource批注,因为SpringBootApplication批注已经包含它们。请检查
application.properties
的路径是否正确,并且您正在传递正确的属性名server.modem。delay
他正在从构造函数调用它。我明白了。下面的答案是正确的,他将需要添加PostConstruct批注。@11thDimension在application.properties的路径上没有问题,还有属性名。另外,如果我用@PostConstruct annotation注释settings()方法,则不会调用该方法。只是为了实现虚拟化,我不会从构造函数调用settings()。