一、

直观的给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简单算法--求100以内素数

    package cn.magicdu.algorithm; /** * 打印素数 * * @author xiaoduc * */ public class Prim { public static ...

  2. JS中null与undefined的区别

    1.typeof操作符 用来检测变量的数据类型 例:typeof 3.14 //返回number typeof [1,2,3]  //返回object 2.null 只有一个值的特殊类型,表示一个空对 ...

  3. JavaScript学习笔记(5)——JavaScript语法之数据类型

    JavaScript 拥有动态类型.这意味着相同的变量可用作不同的类型: var x // x 为 undefined var x = 6; // x 为数字 var x = "Bill&q ...

  4. android 文件的权限

  5. HDU 1058 Humble Number

    Humble Number Problem Description A number whose only prime factors are 2,3,5 or 7 is called a humbl ...

  6. CheckSum

    1.What is Checksum? A check sum is basically a value that is computed from data packet to check its ...

  7. [算法] get_lucky_price price

    int get_lucky_price(int price, const vector & number) 题意大概是给你一个数price,比如1000,然后有unlucky_num,有{1, ...

  8. What are the differences between small, minor, and major updates?

    Following contents are excerpted from the this website and only used for knowledge sharing:  Install ...

  9. c#WebBrowser进阶

    WebBrowser的基本功能就是访问网页,但是由于它本身就不在主线程上面,所以程序判断它什么时候加载完成了,比较麻烦.为此我集合从网上找到的内容,做了一个例子. 其中包括了给WebBrowser设置 ...

  10. css部分基础归纳--学习笔记

    (1)css不区别大小写: (2)颜色值:颜色值可以写成RGB格式,如:color:rgb(255,100,0),也可以写成十六进制格式,如:color:#ff0000.如果十六进制的值是成对重复的可 ...