运行时的值注入

运行时注入Value

Spring提供了两种方式来进行运行时值注入:

  1. Property placeholders
  2. Spring Expression Language (SpEL)
1. 注入外部的Value
1.1 使用Spring提供的Environment来加载配置文件中的配置
package com.soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:/com/soundsystem/app.properties")
public class ExpressiveConfig {
    @Autowired
    Environment env;

    @Bean
    Declare a property source

    public BlankDisc disc() {
        return new BlankDisc(env.getProperty("disc.title"), 
                             env.getProperty("disc.artist"));
    } 
}

@PropertySource注解指明了配置文件的位置

1.2 解析PROPERTY PLACEHOLDERS

@Component
public class BlankDisc {
    public BlankDisc (
        @Value("${disc.title}") String title,
        @Value("${disc.artist}") String artist) {
      this.title = title;
      this.artist = artist;
  )
}

需要配置PropertyPlaceholderConfigurer bean或者PropertySourcesPlaceholderConfigurer bean

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}



  

2. 使用Spring Expression Language

注意:SpEL expressions是被#{}包在里面的哟,不是{}是property placeholder的)

示例:

#{1}

#{T(System).currentTimeMillis()}

#{sgtPeppers.artist}

#{systemProperties['disc.title']}
@Component
public class BlankDisc {

    public BlankDisc(
        @Value("#{systemProperties['disc.title']}") String title,
        @Value("#{systemProperties['disc.artist']}") String artist) {
      this.title = title;
      this.artist = artist;
  )
}


运算符:


image.png

使用正则表达式:

#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.com'}

你可能感兴趣的:(运行时的值注入)