目前采用spring-boot快速开发一个restful api的应用,在配置文件这块卡住了,请求各位大神。
我根据网上的方法尝试了两种都不ok
第一种:基于application.properties配置文件新增
配置文件信息:
application:
des:
key=123456
引用代码信息:
@RestController
@RequestMapping(value="/app")
@EnableAutoConfiguration
public class ServiceConfigController {
@Value("${application.des.key}")
String desKey;
以上方式是根据这篇博客来弄的深入学习微架构
报错:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'application.des.key' in string value "${application.des.key}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 18 more
不知道是识别不了配置文件中的语法还是找不到这个配置。
我还尝试了一下配置书写方式:
application.des.key=1231
也是报错。
第二种还是基于application.properties配置文件
配置文件信息
des.key=123
新建一个java bean
@ConfigurationProperties(prefix="des")
public class DesProperties {
private String key;
//此处省略getter和setter方法
}
引用代码:
@Autowired
DesProperties desProperties;
启动类代码:
@SpringBootApplication
@EnableConfigurationProperties(DesProperties.class)
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class, args);
}
}
启动不报错,但是注解的引用是一个空的对象,可能是我配置的bean没有被注入成功。。表示无解。
第三种方式:采用自定义的配置文件 config.properties
配置文件信息:
des.key=123
java bean配置:
@ConfigurationProperties(prefix = "des",locations = "classpath:config/config.properties")
public class DesProperties {
private String key;
//此处省略getter和setter方法
}
启动类代码:
@SpringBootApplication
@EnableConfigurationProperties(DesProperties.class)
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class, args);
}
}
一样的,启动不报错,引用的时候,是一个空对象。
求各位大神指教。。。。。
我猜是你的目录结构不对吧,你的application.properties应该放在src/main/resource下面
另外可以最好通过指定外部配置文件的方式启动:
有一篇讲spring boot部署的文章可以看看:部署Spring Boot应用,这个网站里有很多关于spring boot的文章,最最重要的是还有代码!