运行时注入Value
Spring提供了两种方式来进行运行时值注入:
- Property placeholders
- 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
<bean id="sgtPeppers"
class="soundsystem.BlankDisc"
c:_title="${disc.title}"
c:_artist="${disc.artist}" />
@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();
}
或
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder />
</beans>
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;
)
}
<bean id="sgtPeppers"
class="soundsystem.BlankDisc"
c:_title="#{systemProperties['disc.title']}"
c:_artist="#{systemProperties['disc.artist']}" />
运算符:
使用正则表达式:
#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.com'}