Spring注入需要初始化,但前面均使用硬编码注入,如:

JavaConfig配置:

  1. package soundSystem;
  2.  
  3. import org.springframework.stereotype.Component;
  4.  
  5. /**
  6. * CompactDisc接口的实现类,此类中定义了CD的名字和作者以及打印相关信息的方法
  7. * @author yan
  8. */
  9. @Component("compactd")//用于扫描来动态生成bean
  10. public class SgtPeppers implements CompactDisc{
  11.  
  12. private String title="K歌之王";
  13. private String artist="陈奕迅";
  14. @Override
  15. public void cdInfo() {
  16. System.out.print("This CD's title:"+title+";artist:"+artist);
  17. }
  18.  
  19. }

xml配置(需要实现setter方法):

  1. <bean id="cd" class="soundSystem.SgtPeppers">
  2. <property name="title" value="L.O.V.E"></property>
  3. <property name="artist" value="May Day"></property>
  4. </bean>

Spring允许注入外部值,这样不用受到硬编码的限制:

--JavaConfig(显式bean)

主要是在配置类中实现:

1.在配置类类名上方添加注解@PropertySource("classpath:/sp.properties"),参数为文件全路径名,properties文件是专门用来存放k-v值对的;

2.在配置类中定义Environment env,并添加@AutoWired注解;

3.在定义bean的方法中使用env.getProperty()方法配置文件(*.properties)中的值来赋给bean作为参数。

  1. package com.spring.config;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.ComponentScan;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.core.env.Environment;
  9.  
  10. import com.spring.custom.Person;
  11.  
  12. @Configuration("com.spring.custom")
  13. @ComponentScan(basePackages={"com.spring"})
  14. @PropertySource("classpath:/sp.properties")
  15. public class CreatureSpingConfig {
  16. @Autowired
  17. Environment env;
  18. @Bean
  19. public Person person(){
  20. return new Person(env.getProperty("name"), env.getProperty("age",Integer.class), env.getProperty("sex"));
  21. }
  22. }

这样就实现了从外部文件注入的目标了。

注:getProperty("key值")返回的是String类型,但并不是所有参数都是String类型,所以这个方法有几个重载形式

解释如下:

  1. public interface PropertyResolver {
  2.  
  3. //是否包含某个属性
  4. boolean containsProperty(String key);
  5.  
  6. //获取属性值 如果找不到返回null
  7. String getProperty(String key);
  8.  
  9. //获取属性值,如果找不到返回默认值
  10. String getProperty(String key, String defaultValue);
  11.  
  12. //获取指定类型的属性值,找不到返回null
  13. <T> T getProperty(String key, Class<T> targetType);
  14.  
  15. //获取指定类型的属性值,找不到返回默认值
  16. <T> T getProperty(String key, Class<T> targetType, T defaultValue);
  17.  
  18. //获取属性值为某个Class类型,找不到返回null,如果类型不兼容将抛出ConversionException
  19. <T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
  20.  
  21. //获取属性值,找不到抛出异常IllegalStateException
  22. String getRequiredProperty(String key) throws IllegalStateException;
  23.  
  24. //获取指定类型的属性值,找不到抛出异常IllegalStateException
  25. <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException;
  26.  
  27. //替换文本中的占位符(${key})到属性值,找不到不解析
  28. String resolvePlaceholders(String text);
  29.  
  30. //替换文本中的占位符(${key})到属性值,找不到抛出异常IllegalArgumentException
  31. String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
  32.  
  33. }

这里列举的是PropertyResolver接口中定义的方法,是因为Environment继承了这个接口,上例中我们使用了第7行和第13行的getProperty的两种重载的形式,当然也可是设置默认值。



--JavaConfig(注解生成bean)演示@Value注解使用方式

实现类:

  1. package com.spring.beans;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.stereotype.Component;
  6. @Component//自动生成bean
  7. public class VCD implements CompactDisc{
  8.  
  9. private String title;
  10. private String artist;
  11. private int year;
  12.  
  13. //定义有参构造
  14. @Autowired//必须写,不写会报错(目前不知原因)
  15. public VCD(@Value("${title}")String title, @Value("${artist}")String artist,@Value("${year}")int year) {
  16. super();
  17. this.title = title;
  18. this.artist = artist;
  19. this.year=year;}
  20. @Override
  21. public void play() {
  22. System.out.println("Playing CD's title is"+title+",the artist is"+artist+",the year is"+year);
  23. }
  24. }

配置类:

  1. package com.spring.config;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Configurable;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.ComponentScan;
  7. import org.springframework.context.annotation.Configuration;
  8. //import org.springframework.context.annotation.ImportResource;
  9. import org.springframework.context.annotation.PropertySource;
  10. import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
  11. import org.springframework.core.env.Environment;
  12.  
  13. @Configuration//表明这是一个Spring的配置类
  14. @ComponentScan(value="com.spring")//表示需要扫描的包,因为演示所用为显式bean,所以其实这里没必要添加此注解
  15. @PropertySource(value="classpath:propertiesSource.properties")
  16. //@ImportResource("classpath:spring.xml")//引入XML配置文件
  17. public class SpringConfig {
  18. /**
  19. * 因为采用混合配置,故注释掉重复bean及无用变量
  20. */
  21. @Autowired
  22. private Environment e;
  23.  
  24. @Bean//要使用@Value注解需要添加此bean
  25. public static PropertySourcesPlaceholderConfigurer pc(){
  26. return new PropertySourcesPlaceholderConfigurer();
  27. }
  28. }

配置文件:

  1. title=L.O.V.E
  2. artist=May Day
  3. year=2006

注:

  1. 要使用@Value需要添加PropertySourcesPlaceholderConfigurer类的bean;
  2. 需要在使用@Value处添加@AutoWired注解,否则会出错。


--XML(显式bean)

此处使用混合配置,以CD为例。

配置类:

  1. package com.spring.config;
  2.  
  3. //import org.springframework.beans.factory.annotation.Autowired;
  4. //import org.springframework.beans.factory.annotation.Configurable;
  5. //import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.ComponentScan;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.ImportResource;
  9. //import org.springframework.context.annotation.PropertySource;
  10. //import org.springframework.core.env.Environment;
  11.  
  12. @Configuration//表明这是一个Spring的配置类
  13. @ComponentScan(value="com.spring")//表示需要扫描的包,因为演示所用为显式bean,所以其实这里没必要添加此注解
  14. //@PropertySource(value="classpath:propertiesSource.properties")
  15. @ImportResource("classpath:spring.xml")//引入XML配置文件
  16. public class SpringConfig {
  17. /**
  18. * 因为采用混合配置,故注释掉重复bean及无用变量
  19. */
  20. // @Autowired
  21. // private Environment e;
  22.  
  23. // @Bean
  24. // public CompactDisc cd(){
  25. // return new VCD(e.getProperty("title"),e.getProperty("artist"));
  26. // }
  27. }

实现类:

  1. package com.spring.beans;
  2. public class VCD implements CompactDisc{
  3.  
  4. private String title;
  5. private String artist;
  6. private int year;
  7. //定义有参构造
  8. public VCD(String title, String artist,int year) {
  9. super();
  10. this.title = title;
  11. this.artist = artist;
  12. this.year=year;
  13. System.out.println("Playing CD's title is"+this.title+",the artist is"+this.artist+",the year is"+this.year);}
  14. @Override
  15. public void play() {}
  16. }

在XML中:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:c="http://www.springframework.org/schema/c"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xmlns:p="http://www.springframework.org/schema/p"
  7. xmlns:context="http://www.springframework.org/schema/context"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd
  12. ">
  13. <context:property-placeholder location="classpath:propertiesSource.properties"/>
  14. <bean id="cd" class="com.spring.beans.VCD" c:_0="${title}" c:_1="${artist}" c:_2="${year}">
  15. </bean>
  16. </beans>

配置文件中:

  1. title=L.O.V.E
  2. artist=May Day
  3. year=2006

这样便可以实现从外部注入属性值了。

注意:

  1. 在XML配置中,要添加<context:property-placeholder/>标签,其属性location的值便为配置文件的路径,这与JavaConfig中的@PropertySource起同样的作用;
  2. 从例子中可以看出,构造器注入,可以使用c-命名空间来设置初始值,格式如:c:_index,index为构造器中参数的索引值,从0开始。而<context:property-placeholder/>标签是专门用来匹配属性占位符的,缺少此标签则不起作用。

2016-10-25 21:20:52

资料参考:

  1. Environment用法:http://blog.csdn.net/hdngbj/article/details/18003001#
  2. 混合配置用法:http://www.cnblogs.com/yw0219/p/5989865.html

Spring-注入外部值的更多相关文章

  1. SSH框架系列:Spring读取配置文件以及获取Spring注入的Bean

    分类: [java]2013-12-09 16:29 1020人阅读 评论(0) 收藏 举报 1.简介 在SSH框架下,假设我们将配置文件放在项目的src/datasource.properties路 ...

  2. spring in action 学习笔记十:用@PropertySource避免注入外部属性的值硬代码化

    @PropertySource的写法为:@PropertySource("classpath:某个.properties文件的类路径") 首先来看一下这个案例的目录结构,重点看带红 ...

  3. Spring(八):Spring配置Bean(一)BeanFactory&ApplicationContext概述、依赖注入的方式、注入属性值细节

    在Spring的IOC容器里配置Bean 配置Bean形式:基于xml文件方式.基于注解的方式 在xml文件中通过bean节点配置bean: <?xml version="1.0&qu ...

  4. spring boot 使用拦截器 无法注入 配置值 、bean问题

    参考:https://www.cnblogs.com/SimonHu1993/p/8360701.html 一定要将 拦截器组件 交给spring容器进行管理,这样才能注入配置值,或者注入bean: ...

  5. spring读取classpath目录下的配置文件通过表达式去注入属性值.txt

    spring读取配置文件: 1. spring加载配置文件: <context:property-placeholder location="classpath:config/syst ...

  6. spring in action 学习十一:property placeholder Xml方式实现避免注入外部属性硬代码化

    这里用到了placeholder特有的一个语言或者将表达形式:${},spring in action 描述如下: In spring wiring ,placeholder values are p ...

  7. spring:为javabean的集合对象注入属性值

    spring:为JavaBean的集合对象注入属性值 在 spring 中可以对List.Set.Map 等集合进行配置,不过根据集合类型的不同,需要使用不同的标签配置对应相应的集合. 1.创建 Ts ...

  8. spring练习,使用Eclipse搭建的Spring开发环境,使用set注入方式为Bean对象注入属性值并打印输出。

    相关 知识 >>> 相关 练习 >>> 实现要求: 使用Eclipse搭建的Spring开发环境,使用set注入方式为Bean对象注入属性值并打印输出.要求如下: ...

  9. spring in action 学习十二:property placeholder 注解的方式实现避免注入外部属性硬代码化

    这里的注解是指@PropertySource这个注解.用@PropertySource这个注解加载.properties文件. 案例的目录结构如下: student.properties的代码如下: ...

随机推荐

  1. ev3dev:设置自动登录wifi

    ev3有时系统不能自动输入wifi密码,在ev3主机上按来按去太麻烦了.看了下官网,解决方案如下: 主要是利用工具:connmanctl,这是一个交互式工具. robot@ev3dev:~$ sudo ...

  2. 【Android】6.2 AlertDialog(警告对话框)

    分类:C#.Android.VS2015: 创建日期:2016-02-08 一.简介 AlertDialog也是Android系统当中常用的对话框之一. 在一个AlertDialog中,可以有一个Bu ...

  3. hdu 5289 Assignment(给一个数组,求有多少个区间,满足区间内的最大值和最小值之差小于k)

    1.区间是一段的,不是断开的哟 2.代码是看着标程写的 3.枚举左端点,二分右端点流程: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L ...

  4. CCTableView(一)

    #ifndef __TABLEVIEWTESTSCENE_H__ #define __TABLEVIEWTESTSCENE_H__ #include "cocos2d.h" #in ...

  5. merge源表数据移植到目标表新表数据中

    merge into dbo.ak_SloteCardTimes a using(select RecordID,CardNO,SloteCardTime from dbo.Tb_CardDate b ...

  6. angular学习笔记(十四)-$watch(2)

    下面来看一个$watch的比较复杂的例子: 还是回到http://www.cnblogs.com/liulangmao/p/3700919.html一开始讲的购物车例子, 给它添加一个计算总价和折扣的 ...

  7. electron-vue 项目搭建的地址

    https://simulatedgreg.gitbooks.io/electron-vue/content/en/ 现在的网址:vue的electron的文件: https://github.com ...

  8. less基本知识总结

    > 一款比较流行的预处理CSS,支持变量.混合.函数.嵌套.循环等特点> [官网](http://lesscss.org/)> [中文网](http://lesscss.cn/)&g ...

  9. vim 删除一整块,vim 删除一整行

    dd: 删除游标所在的一整行(常用) ndd: n为数字.删除光标所在的向下n行,例如20dd则是删除光标所在的向下20行 d1G: 删除光标所在到第一行的所有数据 dG: 删除光标所在到最后一行的所 ...

  10. mysql主从复制的介绍

    引用:https://my.oschina.net/u/255939/blog/505598 MySQL复制就是一台MySQL服务器(slave)从另一台MySQL服务器(master)进行日志的复制 ...