SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-006-给bean运行时注入值(Environment,Property文件)
一、
直观的给bean注入值如下:
@Bean
public CompactDisc sgtPeppers() {
return new BlankDisc(
"Sgt. Pepper's Lonely Hearts Club Band",
"The Beatles");
} < bean id = "sgtPeppers"
class = "soundsystem.BlankDisc"
c: _title = "Sgt. Pepper's Lonely Hearts Club Band"
c: _artist = "The Beatles" / >
都是以硬编码的形式,spring提供了提供了两种方式以运行进注入(1)Property placeholders (2)The Spring Expression Language ( S p EL )
二、Property placeholders
1.app.properties
disc.title=Sgt. Peppers Lonely Hearts Club Band
disc.artist=The Beatles
2.
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 EnvironmentConfig { @Autowired
Environment env; @Bean
public BlankDisc blankDisc() {
return new BlankDisc(
env.getProperty("disc.title"),
env.getProperty("disc.artist"));
} }
3.给定默认值
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.core.env.Environment; @Configuration
public class EnvironmentConfigWithDefaults { @Autowired
Environment env; @Bean
public BlankDisc blankDisc() {
return new BlankDisc(
env.getProperty("disc.title", "Rattle and Hum"),
env.getProperty("disc.artist", "U2"));
} }
4.properties必需有值,否则报错
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.core.env.Environment; @Configuration
public class EnvironmentConfigWithRequiredProperties { @Autowired
Environment env; @Bean
public BlankDisc blankDisc() {
return new BlankDisc(
env.getRequiredProperty("disc.title"),
env.getRequiredProperty("disc.artist"));
} }
5.测试
package com.soundsystem; import static org.junit.Assert.*; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class EnvironmentInjectionTest { @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=EnvironmentConfig.class)
public static class InjectFromProperties { @Autowired
private BlankDisc blankDisc; @Test
public void assertBlankDiscProperties() {
assertEquals("The Beatles", blankDisc.getArtist());
assertEquals("Sgt. Peppers Lonely Hearts Club Band", blankDisc.getTitle());
} } @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=EnvironmentConfigWithDefaults.class)
public static class InjectFromPropertiesWithDefaultValues { @Autowired
private BlankDisc blankDisc; @Test
public void assertBlankDiscProperties() {
assertEquals("U2", blankDisc.getArtist());
assertEquals("Rattle and Hum", blankDisc.getTitle());
} } public static class InjectFromPropertiesWithRequiredProperties { @Test(expected=BeanCreationException.class)
public void assertBlankDiscProperties() {
new AnnotationConfigApplicationContext(EnvironmentConfigWithRequiredProperties.class);
} } @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:placeholder-config.xml")
public static class InjectFromProperties_XMLConfig { @Autowired
private BlankDisc blankDisc; @Test
public void assertBlankDiscProperties() {
assertEquals("The Beatles", blankDisc.getArtist());
assertEquals("Sgt. Peppers Lonely Hearts Club Band", blankDisc.getTitle());
} } }
三、进一步讨论SPRING ’ S E NVIRONMENT
getProperty() is overloaded into four variations:
String getProperty(String key)
String getProperty(String key, String defaultValue)
T getProperty(String key, Class<T> type)
T getProperty(String key, Class<T> type, T defaultValue)
给定默认值
@Bean
public BlankDisc disc() {
return new BlankDisc(
env.getProperty("disc.title", "Rattle and Hum"),
env.getProperty("disc.artist", "U2"));
}
自动转型
int connectionCount =
env.getProperty("db.connection.count", Integer.class, 30);
@Bean
public BlankDisc disc() {
return new BlankDisc(
env.getRequiredProperty("disc.title"),
env.getRequiredProperty("disc.artist"));
}
Here, if either the disc.title property or the disc.artist property is undefined, an
IllegalStateException will be thrown.
检查是否存在
boolean titleExists = env.containsProperty("disc.title");
SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-006-给bean运行时注入值(Environment,Property文件)的更多相关文章
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-007-给BEAN运行时注入值placeholder、@Value
一.用placeholder给bean运行时注入值的步骤 Spring取得placeholder的值是用${...} 1.声明placeholder bean (1)java方式 In order t ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-008-SpEL介绍
一. 1.SpEL expressions are framed with #{ ... } 2.SpEl的作用 Sp EL has a lot of tricks up its sleeves, ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@Scope、ProxyMode
一. Spring的bean默认是单例的 But sometimes you may find yourself working with a mutable class that does main ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除bean自动装配的歧义@Primary
一. 假设有如下三个类实现同一个接口,则自动装配时会产生歧义 @Component public class Cake implements Dessert { ... } @Component pu ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-002-激活PROFILE、设置默认值、@ActiveProfiles
一. Spring honors two separate properties when determining which profiles are active:spring.profiles. ...
- SPRING IN ACTION 第4版笔记-第三章Advancing wiring-001-DataSource在应用和开发环境之间切换 profile
一. DataSource在应用和开发环境的产生方式不同,可以用srping 的profile管理 Spring’s solution for environment-specific beans i ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-009-用SPEL给bean运行时注入依赖值
1.When injecting properties and constructor arguments on beans that are created via component-scanni ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除BEAN自动装配的歧义@QUALIFIER及自定义注解
一. The @Qualifier annotation is the main way to work with qualifiers. It can beapplied alongside @Au ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-003-@Conditional根据条件生成bean及处理profile
一.用@Conditional根据条件决定是否要注入bean 1. package com.habuma.restfun; public class MagicBean { } 2. package ...
随机推荐
- Checkbox 全选、反选
1.全选.反选 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></t ...
- ubuntu系统安装flashplayer
打开浏览器,输入adobe flashplayer 进入官方网站,下载Linux 32-bit, 简体中文, Firefox,下载.tar.gz包. 然后点击立即下载.下载之后找到解压该文件夹,找到 ...
- C# 高精度减法 支持小数(待优化)
是现实思路 1,先小数点补位,8913758923475893274958738945793845-4893127498372459823745324532453245.284929384729837 ...
- OC_NSString
// // main.m // OC_NSString // // Created by qianfeng on 15/6/10. // Copyright (c) 2015年 qianfeng. A ...
- Java架构必会几大技术点(转)
关于学习架构,必须会的几点技术: 1. java反射技术 2. xml文件处理 3. properties属性文件处理 4. 线程安全机制 5. annocation注解 6. 设计模式 7. 代理机 ...
- Android NDK 环境搭建 + 测试例程
懒得废话一大堆概念,关于ADT.NDK的概念要是你不懂,怎么会搜到这里来?所以你只需要根据下面的步骤来,就可以完成NDK环境搭建了. 步骤:(假设你未安装任何相关开发工具,如果已经安装了,就可以跳过) ...
- c++ primer (5)2
第三章 1.头文件不应包含using声明,因为头文件的内容会拷贝到所有引用它的文件中去. 2.初始化string对象的方式: string s1; //默认初始化,s1是一个空串 string s2( ...
- Linux C 程序 两变量值交换(FIVE)
example:1.运算符: #include<stdio.h> int main(){ int a , b , c ,d ; a = ; b = a++;//先赋值给b,a再自增 c = ...
- Less使用——让老司机带你飞
为什么我要使用Less less的作为编写css的工具插件,省时.方便.检测,具体的安装,请参考我的一篇文章<sublime text3 个人使用心得>,里面我讲解了安装方法,使用webs ...
- mysql中的sql时间格式转换
from_unixtime(unix_timestamp, format) 把时间戳转化为指定的格式 as: select from_unixtime(addTime, '%Y-%m-%d %h:%i ...