Spring is injected through an external configuration file notes

Specified path

Use @PropertySource specified configuration file path support properties and XML configuration files, but does not support yml.

Property assignment

Can be directly assigned with annotations @Value of property, $ {} to get the value of the configuration file, SPEL expression # {}.

  • Direct assignment:@Value("name jack")
  • Reads the configuration file:@Value("${user.age}")
  • Specify a default value: @Value("${user.desc:default desc}")it means that if there is no user.descconfiguration, it is assigneddefault desc
  • SPEL expression: @Value("#{'${user.username}'?.toUpperCase()}")represents the value read from the configuration file to uppercase, can not fill, said that if no? user.usernameConfiguration is ignored

example

user.properties content

user.username=my name
user.age=24
#user.desc=

Configuration class

@Component
@PropertySource(value = {"classpath:user.properties"})
public final class UserProperties {
    @Value("name jack")
    private String name;

    @Value("${user.age}")
    private Integer age;

    @Value("#{'${user.username}'?.toUpperCase()}")
    private String username;

    @Value("${user.desc:default desc}")
    private String desc;
}

test

public class Test {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserProperties.class);
    UserProperties bean = context.getBean(UserProperties.class);

    System.out.println(bean);
  }
}

Output

UserProperties(name=name jack, age=24, username=MY NAME, desc=default desc)

Guess you like

Origin www.cnblogs.com/bigshark/p/11280111.html
Recommended