动态注入属性值(一)
来源:互联网 发布:淘宝主图设计技巧 编辑:程序博客网 时间:2024/06/06 03:59
一、在javaConfig中利用Environment注入属性值
1、普通的Student类
public class Student { private int age; private String name; public Student(int age,String name){ this.age=age; this.name=name; } public void display(){ System.out.println("name:"+name+" age:"+age); }}
2、属性值文件 testvalue.properties
test.name=shazimatest.age=3232
3、JavaConfig配置文件
import org.springaction.Student;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:testvalue.properties")public class StudentConfig { //注入environment @Autowired Environment env; @Bean public Student student(){ //如果属性值key不存在,可以设置默认值,没有指定默认值,那获取值就是null;env.getProperty(String key[,String defaultValue]) //实际age类型是int,而获取的类型是String,需要进行转换env.getProperty(String key,Integer.class[,int defaultValue]) //获取的属性值必须要定义 env.getRequiredProperty()方法,如果没有定义则抛出异常 return new Student(env.getProperty("test.age",Integer.class),env.getProperty("test.name")){}; }}
4、测试文件
@RunWith(SpringJUnit4ClassRunner.class)//配置类@ContextConfiguration(classes = StudentConfig.class)public class CDPConfigTest { @Autowired private Student student; @Test public void doP(){ student.display(); }}
二、利用属性占位符注入属性值
1、在JavaConfig中使用占位符
@Configuration//声明属性源@PropertySource("classpath:testvalue.properties")public class StudentConfig {//它能够基于Spring Environment及其属性源来解析占位符 @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean public Student student( @Value("${test.age}") int age, @Value("${test.name}") String name) { return new Student(age,name); }}
2、在XML中通过属性占位符注入属性值
2.1、在XML中增加如下配置
<context:property-placeholder location="testvalue.properties"/> <bean id="student" class="org.springaction.Student" c:name="${test.name}" c:age="${test.age} " />
阅读全文
0 0
- 动态注入属性值(一)
- spring依赖注入方式一:属性注入
- 远程线程注入(一)编写动态链接库
- 远程线程注入(一)编写动态链接库
- action属性注入值
- 注入(一):APC注入
- 属性值注入 还是 构造函数注入?
- Spring高级注入之属性值注入
- Spring高级注入之属性值注入
- Spring高级注入之属性值注入
- [翻译]修改 .NET 对象使其在 IronPython 中表现出动态性(属性注入)
- Spring属性注入(从外部属性文件注入)
- Struts2给属性注入值
- 为Action属性注入值
- struts2 action属性注入值
- 10007---注入属性值细节
- Spring 注入属性值细节
- Spring一IOC(设值注入)
- ThinkPHP5 模型绑定
- 一些字符串函数
- 线性回归python实现
- Docker 学习应用篇之三: Docker的简单实用
- 在Spring2.5+JDK1.8时 使用context.annotation出错
- 动态注入属性值(一)
- python爬虫——多进程multiprocessing
- 【RabbitMQ】——队列模式(2)
- UVA
- 处理技巧+DFS | 计算字符串种类
- Java语言定义了public、protected、private、abstract、static和final这6常用修饰
- 利用pagehelper进行分页查询
- 正则表达式
- mac下virtualbox安装osx系统