一、

直观的给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文件)的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-007-给BEAN运行时注入值placeholder、@Value

    一.用placeholder给bean运行时注入值的步骤 Spring取得placeholder的值是用${...} 1.声明placeholder bean (1)java方式 In order t ...

  2. 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, ...

  3. 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 ...

  4. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除bean自动装配的歧义@Primary

    一. 假设有如下三个类实现同一个接口,则自动装配时会产生歧义 @Component public class Cake implements Dessert { ... } @Component pu ...

  5. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-002-激活PROFILE、设置默认值、@ActiveProfiles

    一. Spring honors two separate properties when determining which profiles are active:spring.profiles. ...

  6. SPRING IN ACTION 第4版笔记-第三章Advancing wiring-001-DataSource在应用和开发环境之间切换 profile

    一. DataSource在应用和开发环境的产生方式不同,可以用srping 的profile管理 Spring’s solution for environment-specific beans i ...

  7. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-009-用SPEL给bean运行时注入依赖值

    1.When injecting properties and constructor arguments on beans that are created via component-scanni ...

  8. 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 ...

  9. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-003-@Conditional根据条件生成bean及处理profile

    一.用@Conditional根据条件决定是否要注入bean 1. package com.habuma.restfun; public class MagicBean { } 2. package ...

随机推荐

  1. 过滤网页中HTML代码的ASP函数

    Function LoseHtml(ContentStr) Dim ClsTempLoseStr,regEx ClsTempLoseStr = Cstr(ContentStr) Set regEx = ...

  2. Android Drawable系列(1):自定义背景以及注意事项

    0. Shape自身属性 android:shape=["rectangle" | "oval" | "line" | "ring ...

  3. linux字符设备驱动学习笔记(一):简单的字符设备驱动

    最近在鼓捣lnux字符设备驱动,在网上搜集的各种关于linux设备驱动的代码和注释,要么是针对2.4的,要么是错误百出,根本就不能运行成功,真希望大家在发博客的时候能认真核对下代码的正确性,特别是要把 ...

  4. asp.net 中excel 导入数据库

    protected void Button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(Sy ...

  5. php ticks 调试应用

    declare(ticks=1); register_tick_function('do_profile'); register_shutdown_function('show_profile'); ...

  6. ###《Effective STL》--Chapter5

    点击查看Evernote原文. #@author: gr #@date: 2014-09-17 #@email: forgerui@gmail.com Chapter5 算法 Topic 30: 确保 ...

  7. aspx文件移动到新建的文件夹中设置路径的问题

    项目中仅仅把aspx移动到想要的文件夹内是会出错的,不用想也知道是路径问题.这里我就说这个路径该如何去修改. 两个地方需要修改:1.母版路径修改方法: <link href="Styl ...

  8. Linux之最最最最基础(包括在虚拟机中安装linux系统)

    这里是以CentOS 6.5  64bit为例(学习用这个,Kali神马的有兴趣自己研究(这个系统是玩渗透用的)) 一 ---->配置Vmware Workstation     自定义--选择 ...

  9. 在Mac OS X中使用VIM开发STM32(2)

    本文原创于http://www.cnblogs.com/humaoxiao,非法转载者请自重! 在我先前的博文⎣在Mac OS X中使用VIM开发STM32(1)⎤中,我们安装完成了MACVIM,这一 ...

  10. thymeleaf 基本语法

    四.标准表达式语法 · 简单表达式 (simple expressions) ${...}  变量表达式 *{...}  选择变量表达式 #{...}  消息表达式 @{...}  链接url表达式 ...