use*_*655 30 spring spring-annotations spring-boot
我有一个Spring Boot应用程序,在其中一个类中,我尝试使用application.properties文件引用属性@Value
.但是,该财产没有得到解决.我查看了类似的帖子,并尝试按照建议,但这没有帮助.这堂课是:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class PrintProperty {
@Value("${file.directory}")
private String fileDirectory;
public void print() {
System.out.println(fileDirectory);
}
}
Run Code Online (Sandbox Code Playgroud)
我有属性file.directory application.properties
.我也有其他领域.
小智 19
我和你一样有同样的问题.这是我的错误代码.
@Component
public class GetExprsAndEnvId {
@Value("hello")
private String Mysecret;
public GetExprsAndEnvId() {
System.out.println("construct");
}
public void print(){
System.out.println(this.Mysecret);
}
public String getMysecret() {
return Mysecret;
}
public void setMysecret(String mysecret) {
Mysecret = mysecret;
}
}
Run Code Online (Sandbox Code Playgroud)
这不是问题,但我们需要像这样使用它:
@Autowired
private GetExprsAndEnvId getExprsAndEnvId;
Run Code Online (Sandbox Code Playgroud)
不是这样的:
getExprsAndEnvId = new GetExprsAndEnvId();
Run Code Online (Sandbox Code Playgroud)
Jes*_*sse 15
确保您的application.properties文件位于src/main/resources/application.properties下.是一种方法.然后按如下方式添加@PostConstruct
示例Application.properties
file.directory = somePlaceOverHere
Run Code Online (Sandbox Code Playgroud)
示例Java类
@ComponentScan
public class PrintProperty {
@Value("${file.directory}")
private String fileDirectory;
@PostConstruct
public void print() {
System.out.println(fileDirectory);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将打印出"somePlaceOverhere"
我想提一下,我使用了春季启动版本1.4.0,因为这个版本你只能写:
@Component
public class MongoConnection {
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private int mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
}
Run Code Online (Sandbox Code Playgroud)
然后随时注入课程.
要读取 application.properties 中的值,我们只需@SpringBootApplication
使用 @Component 或其他类型注释我们的主类以及您正在读取的类。下面是我从中读取值的示例,application.properties
并且在调用 Web 服务时它工作正常。如果您按原样部署相同的代码并尝试从http://localhost:8080/hello进行访问,您将获得存储在 application.properties 中的关键消息值。
package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${message}")
private String message;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping("/hello")
String home() {
return message;
}
}
Run Code Online (Sandbox Code Playgroud)
尝试让我知道
归档时间: |
|
查看次数: |
98478 次 |
最近记录: |