使用@Value注解,可以有三種屬性注入的方式:
1. 使用字面量注入
2. 使用EL表達式注入
3. 使用占位符注入
import org.springframework.beans.factory.annotation.Value; public class Bottle { //使用字面量注入屬性 @Value(value = "red") private String color; //使用el表達式注入屬性 @Value(value = "#{30 / 3.14}") private double diameter; //使用占位符注入屬性,需要在容器中引入配置文件 @Value(value = "${bottle.source}") private String source; …… }
如果在占位符中引入配置文件中的值,必須在容器中聲明配置文件的位置,可以使用@PropertySource注解
/** * 配置類,使用@Value注解進行屬性注入 * 引入配置文件 */ @Configuration @PropertySource(value = {"classpath:/config.properties"}) public class BeanConfig { //使用無參構造器注冊Bottle @Bean(value = "bottle") @Scope("singleton") public Bottle bottle() { return new Bottle(); } }
這樣,從容器中獲取的bean對象就會被注入color、diameter、source屬性。
@Test public void test() { //創建容器 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValueBeanConfig.class); //從容器中獲取Bottle實例 Bottle bottle = (Bottle) applicationContext.getBean("bottle"); //控制台輸出 System.out.println(bottle.toString()); //關閉容器 ((AnnotationConfigApplicationContext)applicationContext).registerShutdownHook(); }
測試結果:
Bottle{color='red', diameter=9.554140127388534, source='laboratory'}
如果容器中聲明了配置文件的位置,還可以使用環境變量獲取其中的值
bottle.source=laboratory bottle.size=1599 bottle.nickname=frankie
//創建容器 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValueBeanConfig.class); //從容器中獲取環境變量 Environment environment = applicationContext.getEnvironment(); String source = environment.getProperty("bottle.source");
