【发布时间】:2018-01-25 03:28:32
【问题描述】:
我正在尝试在 SpringBoot Appilcation 中使用属性。但是当我试图打电话给new MappingProperties().getLogin() 时,我总是得到一个空值。拜托,谁能解释一下我做错了什么?
应用类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@EnableConfigurationProperties
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这是我尝试访问属性的方式
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
@PropertySource("classpath:mapping.properties")
@ConfigurationProperties(prefix = "user")
public class MappingProperties {
private String login;
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login = login;
}
}
这里是我的mapping.properties 文件,它位于src\main\resources\mapping.properties
user.login = /login
还有我的build.gradle
buildscript {
repositories {
maven { url 'http://repo.spring.io/plugins-release' }
}
dependencies {
classpath 'io.spring.gradle:propdeps-plugin:0.0.9.RELEASE'
}
}
plugins {
id 'org.springframework.boot' version '1.5.4.RELEASE'
}
configure(allprojects) {
apply plugin: 'propdeps'
apply plugin: 'propdeps-maven'
apply plugin: 'propdeps-idea'
apply plugin: 'propdeps-eclipse'
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-actuator:1.5.4.RELEASE'
compile 'org.springframework.boot:spring-boot-devtools:1.5.4.RELEASE'
optional "org.springframework.boot:spring-boot-configuration-processor"
testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.4.RELEASE'
}
【问题讨论】:
-
尝试将
@Configuration添加到MappingProperties.java对象...加上@Vitolds 建议的注释 -
@georgesvan 你为什么要这样做?如果它是一个配置文件,那么注释它......
MappingProperties似乎是 -
@Component或@Configuration都没有帮助 -
啊,你在
Application类上也缺少@EnableAutoConfiguration -
不是包含在@SpringBootApplication中吗?
标签: java spring spring-boot properties