Home >Java >javaTutorial >How to solve the problem that SpringBoot's @Value gets invalid application.properties configuration
The reason for the invalidity is mainly to pay attention to the precautions when using @Value:
1. It cannot act on static variables (static);
2. It cannot act on constants (final);
3. It cannot act on non- Used in registered classes (need to use @Componet, @Configuration, etc.);
#4. When using a class with this attribute, it can only be used through @Autowired and new. These configurations will not be automatically injected.
These precautions are also determined by its principles:
There are two important processes during the springboot startup process, as follows:
1. Scan and parse the beans in the container and register them in the beanFactory, just like information registration.
2. Instantiate and initialize these scanned beans.
@Value is parsed in the second stage. BeanPostProcessor defines the interface method that users can operate on the bean before and after bean initialization. One of its important implementation classes, AutowiredAnnotationBeanPostProcessor, as the javadoc says, provides support for the injection function of @Autowired and @Value annotations in the bean.
The following are two ways:
resource.test.imageServer=http://image.everest.com
1. The first one
@Configuration public class EverestConfig { @Value("${resource.test.imageServer}") private String imageServer; public String getImageServer() { return imageServer; } }
2. The second one
@Component @ConfigurationProperties(prefix = "resource.test") public class TestUtil { public String imageServer; public String getImageServer() { return imageServer; } public void setImageServer(String imageServer) { this.imageServer = imageServer; } }
Then inject it where needed
@Autowired private TestUtil testUtil; @Autowired private EverestConfig everestConfig; @GetMapping("getImageServer") public String getImageServer() { return testUtil.getImageServer(); // return everestConfig.getImageServer(); }
@Value("${spring.datasource.url}") private String url;
gets the value as NUll.
Don’t use the new method to create the tool class (DBUtils) object, but use the @Autowired method to let springboot manage it, and add @Component to the tool class. Do not add static to the defined attribute variables.
@Autowired private DBUtils jdbc; @Component public class DBUtils{ @Value("${spring.datasource.url}") private String url; }
The above is the detailed content of How to solve the problem that SpringBoot's @Value gets invalid application.properties configuration. For more information, please follow other related articles on the PHP Chinese website!