How spring customizes @ Value to be resolved to
In view of how spring customizes @ Value to be parsed, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a simpler and easier way.
Spring customization lets @ Value resolve to
@ Value can assign values to fields
Background
@ Value is usually combined with @ PropertySource (value = "db.properties") to use read configuration injection parameters, so how can we assign values automatically if our values are other stores?
Realization principle
The implementation is very simple.
/ / automatically inject this object @ Autowired private Environment environment; @ PostConstruct public void init () {/ / get some objects MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment) .getPropertySources (); PropertySourceFactory factory = BeanUtils.instantiateClass (DefaultPropertySourceFactory.class); / / construct pathResource PathResource pathResource = new PathResource ("/ Users/xx/soft/sp.properties") Try {org.springframework.core.env.PropertySource sd = factory.createPropertySource ("sd", new EncodedResource (pathResource)); / / set the value propertySources.addFirst (sd);} catch (IOException e) {e.printStackTrace ();}}
Mainly get the PropertySource object through the code, and then get the environment object, and set the value.
Spring4 Custom @ Value function
The Spring version of 4.3.10.RELEASE used in this article
@ Value is very powerful in Spring, you can inject a configuration item, you can reference the Bean in the container (call its method), or you can do some simple operations
The following is a simple demo
Demonstrate the use of @ Value import org.springframework.stereotype.Service; / * Test Bean * / @ Service ("userService") public class UserService {public int count () {return 10;} public int max (int size) {int count = count (); return count > size? Count: size;}} import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class AppRunner implements InitializingBean {/ * refers to a configuration item * / @ Value ("${app.port}") private int port; / * calls a bean method of the container to get the value * / @ Value ("# {userService.count ()}") private int userCount / * call a bean method of the container, and pass in the value of a configuration item as the parameter * / @ Value ("# {userService.max (${app.size})}") private int max; / * simple operation * / @ Value ("# {${app.size})"