Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use @ PropertySource to read a configuration file

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to use @ PropertySource to read configuration files". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use @ PropertySource to read configuration files.

@ PropertySource read configuration file is injected through @ Value parameter

There are parameter files as follows: test.properties

Project.author=wpfcproject.create_time=2018/3/29

Read the corresponding data in the system and inject it into the attribute

@ Configuration@ComponentScan ("cn.edu.ntu") @ PropertySource ("classpath:test.properties") public class ElConfig {@ Value ("# {systemProperties ['os.name']}") private String osName / / to use @ Value to inject attributes with the ${} placeholder, this bean is required (PropertySourcesPlaceholderConfigurer), / / this is the placeholder bean, / / another way is to directly getProperty ('key') @ Value ("${project.author}") public String author; @ Autowired private Environment environment without using the value variable. / / You need this if you use @ PropertySource + @ Value @ Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer () {return new PropertySourcesPlaceholderConfigurer ();} public void printProperties () {System.out.println ("os name:" + osName); System.out.println ("author:" + author); System.out.println ("env:" + environment.getProperty ("project.create_time"));}}

Test method:

Public class MainApplication {public static void main (String [] args) {AnnotationConfigApplicationContext context = null; context = new AnnotationConfigApplicationContext (ElConfig.class); ElConfig bean = context.getBean (ElConfig.class); bean.printProperties ();}}

Test results:

Os name: Windows 7author: wpfcenv: 2018-3-29

@ Import introduces the configuration class of javaConfig configuration

@ ImportResource introduces the configuration file corresponding to xml

Spring read configuration @ Value, @ PropertySource, @ ConfigurationProperties use

There are many ways for Spring (Boot) to get parameters, of which the most familiar one is @ Value, which is powerful.

Today, we will conduct a detailed literacy campaign aimed at @ Value, which is the longest used by us, and @ PropertySource, @ ConfigurationProperties and other related annotations that may be rarely used, hoping to help us get home and use it more smoothly.

@ Value

The injection of @ Value annotations is very powerful, either with the help of configuration files or directly

Inject a normal string

@ Value ("normal") private String normal; / / normal (obviously this injection doesn't make much sense)

Inject operating system properties

@ Value ("# {systemProperties ['os.name']}") private String systemPropertiesName; / / effect is equivalent because the spring template puts the system variable into Enviroment@Value ("${os.name}") private String systemPropertiesName

Injection expression result

@ Value ("# {T (java.lang.Math). Random () * 100.0}") private double randomNumber; / / 41.29185128620939

Inject properties of other Bean: the name property of the Person class

@ Bean public Person person () {Person person = new Person (); person.setName ("fangshixiang"); return person;} / / injection attribute @ Value ("# {person.name}") private String personName; @ Test public void contextLoads () {System.out.println (personName); / / fangshixiang}

Inject file resources

Place a jdbc.properties configuration file under resources. Then it can be injected directly.

@ Value ("classpath:jdbc.properties") private Resource resourceFile; / / inject file resources @ Test public void contextLoads () throws IOException {System.out.println (resourceFile); / / classpath resource [jdbc.properties] String s = FileUtils.readFileToString (resourceFile.getFile (), StandardCharsets.UTF_8); System.out.println (s) / / output: / / db.username=fangshixiang / / db.password=fang / / db.url=jdbc:mysql://localhost:3306/mytest / / db.driver-class-name=com.mysql.jdbc.Driver}

Inject Url resources

@ Value ("http://www.baidu.com") private Resource testUrl; / / injecting URL resources @ Test public void contextLoads () {System.out.println (testUrl); / / URL [http://www.baidu.com]} @ Value] the difference between $and #

Syntax:

Syntax differences between ${properties} and # {SpEL}

${property: default_value}

# {obj.property?: default_value} indicates that SpEl expressions are usually used to get properties of bean or to call a method of bean. And, of course, it can represent constants.

For normal use, I will not introduce too much here, but now I will introduce some abnormal situations.

${properties} `: this is relatively simple. If the key cannot be found, the startup will fail. If you want to start normally when you can't find it, you can use colon + default value.

# {obj.property?: default_value}

@ Value ("# {person}") private Person value; @ Test public void contextLoads () {System.out.println (value); / / Person (name=fangshixiang, age=null, addr=null, hobby=null)}

We found that this is very powerful and can directly inject an object in the container directly. It's just that we may not usually do this.

If you change it to person1, and you can't find the bean in the container, you will start to report an error. @ Value ("# {person1?:null}") this will not work either, because if person1 cannot find it, it will report an error.

@ Value ("# {person.name}") private String personName; @ Value ("# {person.age}") private String perAge; / / injection default @ Value ("# {person.age?:20}") private String perAgeDefault; / / if the age22 key does not exist, startup will definitely report an error / / @ Value ("# {person.age22?:20}") / / private String perAgeDefault22 @ Test public void contextLoads () {System.out.println (personName); / / fangshixiang System.out.println (perAge); / / null System.out.println (perAgeDefault); / / 20}

To get the cascading properties, the following two methods are ok:

@ Value ("# {person.parent.name}") private String parentName1; @ Value ("# {person ['parent.name']}") private String parentName2; @ Test public void contextLoads () {System.out.println (parentName1); / / fangshixiang System.out.println (parentName2); / / fangshixiang}

Use both: # {'${}'}

Pay attention to the combination of syntax and single quotation marks, not upside down.

With the combination of the two, you can take advantage of the characteristics of SpEL to write some complex expressions, such as:

@ Value ("# {${os.name}'+'_'+ person.name}") private String age; @ Test public void contextLoads () {System.out.println (age); / / Windows 10_fangshixiang} @ PropertySource: load the configuration property source

This annotation is also very powerful. When used, it can realize the separation and attention of configuration files, greatly improve the efficiency of development and realize centralized management.

The simplest application, combined with @ Value injection attribute values (and the most common application)

Load the configuration file through @ PropertySource and get it using @ Value

Configuration@PropertySource ("classpath:jdbc.properties") public class PropertySourceConfig {@ Value ("${db.url}") private String dbUrl; @ PostConstruct public void postConstruct () {System.out.println (dbUrl); / / jdbc:mysql://localhost:3306/mytest}}

@ PropertySource introduction to each attribute

Value: array. Specify the location of the configuration file. Prefixes such as classpath: and file: are supported. Spring discovery begins with classpath, so you end up using ClassPathResource, a subclass of Resource. If it starts with file, the final class to use is FileSystemResource

IgnoreResourceNotFound: the default is false. It means that if the file is not found, it will report an error, but if it is changed to true, it will not report an error. It is recommended that false be retained

Encoding: the code loaded in. Generally, it does not need to be set, but can be set to UTF-8 and so on.

Factory: the default value is DefaultPropertySourceFactory.class.

@ Override public PropertySource createPropertySource (String name, EncodedResource resource) throws IOException {return (name! = null? New ResourcePropertySource (name, resource): new ResourcePropertySource (resource);}

In fact, the source code is nothing special. The important and difficult points are as follows:

1. When will DefaultPropertySourceFactory be loaded by Spring?

2. When were both name and resource assigned?

This article throws out these two questions, the specific reasons will be reflected in the subsequent analysis of the source code related articles.

It is important to note that the loading time of PropertySourceFactory is earlier than that of the Spring Beans container, so the implementation cannot rely on Spring's IOC.

@ PropertySource multi-context configuration and expression use (spring.profiles.active)

Method 1: it can be configured like this.

@ PropertySource ("classpath:jdbc-$ {spring.profiles.active} .properties")

Programmers do not need to care about the address, account number and other information of the database in the production environment when developing, and can run in different environments with one build.

@ ConfigurationProperties

Note: the above are actually the functions provided by Spring Framwork. And @ ConfigurationProperties is provided by Spring Boot. Including @ EnableConfigurationProperties is also available in Spring Boot. It plays a key role in automatic configuration.

ConfigurationPropertiesBindingPostProcessor configures attribute values for Bean annotated with @ ConfigurationProperties annotations.

Sometimes there is a situation where we want to read and automatically encapsulate the information of the configuration file into an entity class, so it is much easier for us to use it in the code. At this time, we can use @ ConfigurationProperties, which can automatically encapsulate the configuration information of the same kind into an entity class.

This annotation is widely used in the automatic configuration of Spring Boot.

For example, the automatic configuration of SpringMVC:

@ ConfigurationProperties (prefix = "spring.mvc") public class WebMvcProperties {} / / loading method @ Configuration @ Conditional (DefaultDispatcherServletCondition.class) @ ConditionalOnClass (ServletRegistration.class) / / this note is used here It can be argued that the Bean of WebMvcProperties is loaded into the container ~ ~ / / WebMvcProperties uses `@ ConfigurationProperties (prefix = "spring.mvc")` @ EnableConfigurationProperties (WebMvcProperties.class) / / loads the configuration file protected static class DispatcherServletConfiguration {} of MVC

It seems that we can see some ways in which the annotations should be used.

Explanation: the two kinds mentioned here are only the most commonly used. In fact, as long as you can inject Bean into the container, it is one way. For example, the @ EnableConfigurationProperties method above is also ok.

The explanation of @ EnableConfigurationProperties will be reflected in the annotation-driven Spring related blog posts.

Add to the class, need to be used in conjunction with the @ Component annotation. The code is as follows

Com.example.demo.name=$ {aaa:hi} com.example.demo.age=11com.example.demo.address [0] = Beijing # pay attention to the representation of array List Map/Obj way you can try com.example.demo.address [1] = Shanghai com.example.demo.address [2] = Guangzhou com.example.demo.phone.number=1111111

Java Code:

@ Component@ConfigurationProperties (prefix = "com.example.demo") public class People {private String name; private Integer age; private List address; private Phone phone;}

Declare it through @ Bean. Here we can add it to the startup class as follows

Bean @ ConfigurationProperties (prefix = "com.example.demo") public People people () {return new People ();}

You don't need to use @ EnableConfigurationProperties to open it in these ways.

Details: the field of Bean must have a get/set method. Please note ~ ~

In addition, there is a way to combine @ PropertySource, which is a perfect match.

@ Component@PropertySource ("classpath:config/object.properties") @ ConfigurationProperties (prefix = "obj") public class ObjectProperties {}

The meaning of the name of the rest of the attributes is mentioned here:

IgnoreInvalidFields

IgnoreNestedProperties

IgnoreUnknownFields

Simple understanding:

@ ConfigurationProperties automatically encapsulates all attribute values under a certain class name of the application configuration file into an entity class.

@ Value encapsulates a property value needed in the application configuration file into java code for use.

Different application scenarios:

If you just need to get a value in a configuration file or set a specific value in a business, you can use @ Value

If a large number of attribute values in a JavaBean want to be mapped to the configuration file, you can use @ ConfigurationProperties

At this point, I believe you have a better understanding of "how to use @ PropertySource to read configuration files". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report