一、

直观的给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. java多线程总结四:volatile、synchronized示例

    1.synchronized保证同步 先看一个生成偶数的类 <span style="font-size:16px;">package demo.thread; /** ...

  2. asp.net 控件 导出 excel

    //导出EXCEL protected void btnDaoChu_Click(object sender, EventArgs e) { HttpContext.Current.Response. ...

  3. 关于main函数的定义

     很多人甚至市面上的一些书籍,都使用了void main( ),其实这是错误的.C/C++中从来没有定义过void main( ).C++之父Bjarne Stroustrup在他的主页上的FAQ中明 ...

  4. 信息收集->DNS分析->dnsdict6

    如何获取域名的IPV4/IPV6地址之dnsdict6的使用 dnsdict6是一个用于获取网站信息的工具.dnsdict6可以扫描网站并显示有多少域或者子域,也可以扫描ipv6/ipv4地址.dns ...

  5. 解决:error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'

    在使用 deamon@deamon-H55M-S2:/usr/bin$ mysqladmin -u root -p shutdown 关闭MySQL之后试图通过: deamon@deamon-H55M ...

  6. NUnit单元测试

    单元测试对程序员来说是非常重要的一门技术,但是在实际编程中却往往被程序员所忽视.微软的VS开发工具为我们提供了强大的单元测试环境,在VS当中可以直接对类库项目进行测试,极大的方便了程序员的自我纠错能力 ...

  7. JS 获取 路径参数 传入 参数名 截取 & 和 # 之前 字符

    function getQueryStringByName(name) { var result = location.search.match(new RegExp("[\?\&] ...

  8. 关于css中overflow:hidden的使用

    overflow:hidden有两个用处经常用到: 1.通过设定自身的高度,加上overflow:hidden可以隐藏超过容器本身的内容:     但是,小编在以往的使用中,发现了一个问题,只要父级容 ...

  9. H5 App如此强悍,要降薪的恐怕已不只是iOS程序员

    2015年的最后几天,移动开发圈里最为火爆的话题之一无疑是“iOS程序员月薪降至12K”这则报道. 有人认为这是O2O创业遇冷所致,也有人认为这是iOS生态过于封闭致使智能硬件等新领域对iOS开发者的 ...

  10. UI设计的奥义

    个人觉得一个好的UI应该具备如下特点 1.符合人类认知行为 2.契合人体生物学 3.平滑,流畅 4.适当的交互会让你的应用更加成功 5.动态的内容才是招蜂引蝶的资本