当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Spring Read value from properties file into @SpringBootApplication class

问题描述:

I've a SpringBootApplication and I want read a value from my property file.

My @SpringBootApplication class is this:

@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;

}

}

Unfortunately in in method called "settings" the value of property modemSmsDelay is 0 also if in my application.properties file it's 1000.

In other parts of my app I can read values without problems.

==== UPDATE =====

I solved the problem. Infact my code works, is not needed @PostConstruct to make @Value tag work, also if it's desiderable in several circustances.

I had a problem in my Spring configuration that prevented the execution of all annotation as @PostConstruct,@Autowire, etc.

I noticed this from log where Spring printed a Warning message.

网友答案:

Try putting the @PostConstruct annotation on your settings() method rather than calling it from the constructor. This will cause the method to be called automagically after the constructor exits.

网友答案:

This works for me :

@Resource private Environment environment;

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);
  }

}

And in my application.properties

contentType=some_value
rest.url=http://localhost/....

HTH

分享给朋友:
您可能感兴趣的文章:
随机阅读: