一、
直观的给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
1 disc.title=Sgt. Peppers Lonely Hearts Club Band 2 disc.artist=The Beatles
2.
1 package com.soundsystem; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.context.annotation.Bean; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.context.annotation.PropertySource; 7 import org.springframework.core.env.Environment; 8 9 @Configuration 10 @PropertySource("classpath:/com/soundsystem/app.properties") 11 public class EnvironmentConfig { 12 13 @Autowired 14 Environment env; 15 16 @Bean 17 public BlankDisc blankDisc() { 18 return new BlankDisc( 19 env.getProperty("disc.title"), 20 env.getProperty("disc.artist")); 21 } 22 23 }
3.
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:c="http://www.springframework.org/schema/c" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 8 9 <context:property-placeholder 10 location="com/soundsystem/app.properties" /> 11 12 <bean class="com.soundsystem.BlankDisc" 13 c:_0 = "${disc.title}" 14 c:_1 = "${disc.artist}"/> 15 16 </beans>
三、进一步讨论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");
时间: 2024-10-05 05:31:39