As the title, my custom properties:
#app settings
my.chassisNum=10
java code:
@PropertySource("classpath:appconf.properties")
@ConfigurationProperties(prefix = "my" )
@Component
public class AppConfig {
private String chassisNum;
public String getChassisNum() {
return this.chassisNum;
}
public void setChassisNum(String chassisNum) {
this.chassisNum = chassisNum;
}
}
when Spring Boot start completed, I got the "chassisNum" value is 10. when I got it in other place when spring-boot not start completed, it get "null"
@Component
public class CreateBaseFolder {
private final Logger logger = LogManager.getLogger(CreateBaseFolder.class);
private File f;
@Autowired
AppConfig appconf;
public CreateBaseFolder() {
System.out.println(appconf.getChassisNum());
}
i try many way to get it value,but is false.such as :implements InitializingBean, @DependsOn....
Assume you has application.properties
with content:
foo.bar=Jerry
You will use annotation @Value
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GetPropertiesBean {
private final String foo;
@Autowired
public GetPropertiesBean(@Value("${foo.bar}") String foo) {
this.foo = foo;
System.out.println(foo);
}
}
Of course, we need an entry point
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Then run class Application as Spring Boot application, component is autoload, you will see result at console screen
Jerry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With