运行时注入值

依赖注入:①将一个bean注入到另一个bean的属性或构造器参数中。【通常用来指将一个对象与另外一个对象进行关联】
②将一个 【值】注入到bean的属性或者构造器参数中。<bean id="" class=""><property name="属性名" value="注入的参数值" /> </bean>
============= 运行时注值=============
Spring提供了两种运行时注值的方式:
①属性占位符(property placeholder)
②Spring表达式语言(SpEL)
直接从Environment中检索属性
package demo2;

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:env.properties")
public class DemoConfig {
@Autowired
Environment environment;
@Bean
public User user(){
return new User( environment.getProperty("name"),environment.getProperty("", Integer.class));
}
//environment.containsProperty("")
}
【properties文件
name=\u8FD9\u4E2A
age=12】
1、解析属性占位符
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:env.properties" />
<bean id="user" class="demo2.User">
<property name="name" value="${name}"></property>
<property name="age" value="${age}"></property>
</bean>
</beans>
在configuration类中 @Value("#{configProperties[name]}")
【2、SpringEL表达式语言进行装配】
①SpringEL的特性:
*使用bean的ID来引用bean
*调用方法来访问对象的属性
*对值进行算术、关系和逻辑运算
*正则表达式匹配 *集合操作
②SpringEL表达式要放到 "#{...}" 之中
示例:
#{T(System).currentTimeMillis()}---T()表达式会将java.lang.System视为java中对应的类型,因此可以调用其static修饰的currentTimeMills()方法。
#{bean.属性}---在Spring中创建的bean可以使用SpringEL获取器属性值
#{普通字面值}---如String,int,浮点类型,boolean
#{值1 > 值2 ? "winner":"loser"}---三元运算符
当前在#{}中,一般的加减乘除大小于都能用

猜你喜欢

转载自blog.csdn.net/November22/article/details/54980828