测试例子

packagecom.hjzgg.auth.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.PropertySource;importorg.springframework.core.env.Environment;importorg.springframework.util.StringUtils;importjava.lang.reflect.Field;importjava.util.ArrayList;importjava.util.List;/*** Created by hujunzheng on 2017/6/22.*/@Configuration
@PropertySource("classpath:conf/config.properties")public classSystemConfig {public static classUser {public staticString NAME;public static intAGE;public static intUSER_ID;public staticString ADDRESS;}@AutowiredprivateEnvironment env;@Beanpublic SystemConfig oauthSystemConfig() throwsIllegalAccessException {setStaticPropertiesValue(SystemConfig.class);Class<?>[] clazzs = SystemConfig.class.getClasses();for(Class clazz: clazzs) {setStaticPropertiesValue(clazz);}return null;}private void setStaticPropertiesValue(Class<?> clazz) throwsIllegalAccessException {Field[] fields=clazz.getDeclaredFields();for(Field field : fields) {String key= field.getName().toLowerCase().replace("_", ".");String value=env.getProperty(key);if(StringUtils.isEmpty(value)) {continue;}if (field.getType() == List.class) {String[] values= value.split(",");List<String> vlist = new ArrayList<String>();for(String tvalue : values) {if (!StringUtils.isEmpty(tvalue)) {vlist.add(tvalue);}}field.set(null, vlist);}if (field.getType() == String[].class) {String[] values= value.split(",");List<String> vlist = new ArrayList<String>();for(String tvalue : values) {if (!StringUtils.isEmpty(tvalue)) {vlist.add(tvalue);}}field.set(null, vlist.toArray(newString[] {}));}if (field.getType() == String.class) {field.set(null, value);}if (field.getType() == Integer.class) {field.set(null, Integer.valueOf(value));}if (field.getType() == Float.class) {field.set(null, Float.valueOf(value));}if (field.getType() == Double.class) {field.set(null, Double.valueOf(value));}}}
}

Configuration源码说明

packageorg.springframework.context.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;/*** Indicates that a class declares one or more {@linkBean @Bean} methods and may be processed* by the Spring container to generate bean definitions and service requests for those* beans at runtime, for example:* <pre class="code">* &#064;Configuration* public class AppConfig {*     &#064;Bean*     public MyBean myBean() {*         // instantiate, configure and return bean ...*     }* }</pre>** <h2>Bootstrapping {@code@Configuration} classes</h2>* <h3>Via {@codeAnnotationConfigApplicationContext}</h3>* {@code@Configuration} classes are typically bootstrapped using either* {@linkAnnotationConfigApplicationContext} or its web-capable variant,* {@linkorg.springframework.web.context.support.AnnotationConfigWebApplicationContext* AnnotationConfigWebApplicationContext}.* A simple example with the former follows:* <pre class="code">* AnnotationConfigApplicationContext ctx =*     new AnnotationConfigApplicationContext();* ctx.register(AppConfig.class);* ctx.refresh();* MyBean myBean = ctx.getBean(MyBean.class);* // use myBean ...</pre>** See {@linkAnnotationConfigApplicationContext} Javadoc for further details and see* {@linkorg.springframework.web.context.support.AnnotationConfigWebApplicationContext* AnnotationConfigWebApplicationContext} for {@codeweb.xml} configuration instructions.** <h3>Via Spring {@code<beans>} XML</h3>* <p>As an alternative to registering {@code@Configuration} classes directly against an* {@codeAnnotationConfigApplicationContext}, {@code@Configuration} classes may be* declared as normal {@code<bean>} definitions within Spring XML files:* <pre class="code">* {@code* <beans>*    <context:annotation-config/>*    <bean class="com.acme.AppConfig"/>* </beans>}</pre>** In the example above, {@code<context:annotation-config/>} is required in order to* enable {@linkConfigurationClassPostProcessor} and other annotation-related* post processors that facilitate handling {@code@Configuration} classes.** <h3>Via component scanning</h3>* <p>{@code@Configuration} is meta-annotated with {@linkComponent @Component}, therefore* {@code@Configuration} classes are candidates for component scanning (typically using* Spring XML's {@code<context:component-scan/>} element) and therefore may also take* advantage of {@linkAutowired @Autowired}/{@linkjavax.inject.Inject @Inject}* at the field and method level (but not at the constructor level).* <p>{@code@Configuration} classes may not only be bootstrapped using* component scanning, but may also themselves <em>configure</em> component scanning using* the {@linkComponentScan @ComponentScan} annotation:* <pre class="code">* &#064;Configuration* &#064;ComponentScan("com.acme.app.services")* public class AppConfig {*     // various &#064;Bean definitions ...* }</pre>** See {@linkComponentScan @ComponentScan} Javadoc for details.*** <h2>Working with externalized values</h2>* <h3>Using the {@codeEnvironment} API</h3>* Externalized values may be looked up by injecting the Spring* {@linkorg.springframework.core.env.Environment Environment} into a* {@code@Configuration} class using the {@code@Autowired} or the {@code@Inject}* annotation:* <pre class="code">* &#064;Configuration* public class AppConfig {*     &#064Inject Environment env;**     &#064;Bean*     public MyBean myBean() {*         MyBean myBean = new MyBean();*         myBean.setName(env.getProperty("bean.name"));*         return myBean;*     }* }</pre>** Properties resolved through the {@codeEnvironment} reside in one or more "property* source" objects, and {@code@Configuration} classes may contribute property sources to* the {@codeEnvironment} object using* the {@linkorg.springframework.core.env.PropertySources @PropertySources} annotation:* <pre class="code">* &#064;Configuration* &#064;PropertySource("classpath:/com/acme/app.properties")* public class AppConfig {*     &#064Inject Environment env;**     &#064;Bean*     public MyBean myBean() {*         return new MyBean(env.getProperty("bean.name"));*     }* }</pre>** See {@linkorg.springframework.core.env.Environment Environment}* and {@linkPropertySource @PropertySource} Javadoc for further details.** <h3>Using the {@code@Value} annotation</h3>* Externalized values may be 'wired into' {@code@Configuration} classes using* the {@linkValue @Value} annotation:* <pre class="code">* &#064;Configuration* &#064;PropertySource("classpath:/com/acme/app.properties")* public class AppConfig {*     &#064Value("${bean.name}") String beanName;**     &#064;Bean*     public MyBean myBean() {*         return new MyBean(beanName);*     }* }</pre>** This approach is most useful when using Spring's* {@linkorg.springframework.context.support.PropertySourcesPlaceholderConfigurer* PropertySourcesPlaceholderConfigurer}, usually enabled via XML with* {@code<context:property-placeholder/>}.  See the section below on composing* {@code@Configuration} classes with Spring XML using {@code@ImportResource},* see {@linkValue @Value} Javadoc, and see {@linkBean @Bean} Javadoc for details on working with* {@codeBeanFactoryPostProcessor} types such as* {@codePropertySourcesPlaceholderConfigurer}.** <h2>Composing {@code@Configuration} classes</h2>* <h3>With the {@code@Import} annotation</h3>* <p>{@code@Configuration} classes may be composed using the {@linkImport @Import} annotation,* not unlike the way that {@code<import>} works in Spring XML. Because* {@code@Configuration} objects are managed as Spring beans within the container,* imported configurations may be injected using {@code@Autowired} or {@code@Inject}:* <pre class="code">* &#064;Configuration* public class DatabaseConfig {*     &#064;Bean*     public DataSource dataSource() {*         // instantiate, configure and return DataSource*     }* }** &#064;Configuration* &#064;Import(DatabaseConfig.class)* public class AppConfig {*     &#064Inject DatabaseConfig dataConfig;**     &#064;Bean*     public MyBean myBean() {*         // reference the dataSource() bean method*         return new MyBean(dataConfig.dataSource());*     }* }</pre>** Now both {@codeAppConfig} and the imported {@codeDatabaseConfig} can be bootstrapped* by registering only {@codeAppConfig} against the Spring context:** <pre class="code">* new AnnotationConfigApplicationContext(AppConfig.class);</pre>** <h3>With the {@code@Profile} annotation</h3>* {@code@Configuration} classes may be marked with the {@linkProfile @Profile} annotation to* indicate they should be processed only if a given profile or profiles are* <em>active</em>:* <pre class="code">* &#064;Profile("embedded")* &#064;Configuration* public class EmbeddedDatabaseConfig {*     &#064;Bean*     public DataSource dataSource() {*         // instantiate, configure and return embedded DataSource*     }* }** &#064;Profile("production")* &#064;Configuration* public class ProductionDatabaseConfig {*     &#064;Bean*     public DataSource dataSource() {*         // instantiate, configure and return production DataSource*     }* }</pre>** See {@linkProfile @Profile} and {@linkorg.springframework.core.env.Environment Environment}* Javadoc for further details.** <h3>With Spring XML using the {@code@ImportResource} annotation</h3>* As mentioned above, {@code@Configuration} classes may be declared as regular Spring* {@code<bean>} definitions within Spring XML files. It is also possible to* import Spring XML configuration files into {@code@Configuration} classes using* the {@linkImportResource @ImportResource} annotation. Bean definitions imported from XML can be* injected using {@code@Autowired} or {@code@Import}:* <pre class="code">* &#064;Configuration* &#064;ImportResource("classpath:/com/acme/database-config.xml")* public class AppConfig {*     &#064Inject DataSource dataSource; // from XML**     &#064;Bean*     public MyBean myBean() {*         // inject the XML-defined dataSource bean*         return new MyBean(this.dataSource);*     }* }</pre>** <h3>With nested {@code@Configuration} classes</h3>* {@code@Configuration} classes may be nested within one another as follows:* <pre class="code">* &#064;Configuration* public class AppConfig {*     &#064;Inject DataSource dataSource;**     &#064;Bean*     public MyBean myBean() {*         return new MyBean(dataSource);*     }**     &#064;Configuration*     static class DatabaseConfig {*         &#064;Bean*         DataSource dataSource() {*             return new EmbeddedDatabaseBuilder().build();*         }*     }* }</pre>** When bootstrapping such an arrangement, only {@codeAppConfig} need be registered* against the application context. By virtue of being a nested {@code@Configuration}* class, {@codeDatabaseConfig} <em>will be registered automatically</em>. This avoids* the need to use an {@code@Import} annotation when the relationship between* {@codeAppConfig} {@codeDatabaseConfig} is already implicitly clear.** <p>Note also that nested {@code@Configuration} classes can be used to good effect* with the {@code@Profile} annotation to provide two options of the same bean to the* enclosing {@code@Configuration} class.** <h2>Configuring lazy initialization</h2>* <p>By default, {@code@Bean} methods will be <em>eagerly instantiated</em> at container* bootstrap time.  To avoid this, {@code@Configuration} may be used in conjunction with* the {@linkLazy @Lazy} annotation to indicate that all {@code@Bean} methods declared within* the class are by default lazily initialized. Note that {@code@Lazy} may be used on* individual {@code@Bean} methods as well.** <h2>Testing support for {@code@Configuration} classes</h2>* The Spring <em>TestContext framework</em> available in the {@codespring-test} module* provides the {@code@ContextConfiguration} annotation, which as of Spring 3.1 can* accept an array of {@code@Configuration} {@codeClass} objects:* <pre class="code">* &#064;RunWith(SpringJUnit4ClassRunner.class)* &#064;ContextConfiguration(classes={AppConfig.class, DatabaseConfig.class})* public class MyTests {**     &#064;Autowired MyBean myBean;**     &#064;Autowired DataSource dataSource;**     &#064;Test*     public void test() {*         // assertions against myBean ...*     }* }</pre>** See TestContext framework reference documentation for details.** <h2>Enabling built-in Spring features using {@code@Enable} annotations</h2>* Spring features such as asynchronous method execution, scheduled task execution,* annotation driven transaction management, and even Spring MVC can be enabled and* configured from {@code@Configuration}* classes using their respective "{@code@Enable}" annotations. See* {@linkorg.springframework.scheduling.annotation.EnableAsync @EnableAsync},* {@linkorg.springframework.scheduling.annotation.EnableScheduling @EnableScheduling},* {@linkorg.springframework.transaction.annotation.EnableTransactionManagement @EnableTransactionManagement},* {@linkorg.springframework.context.annotation.EnableAspectJAutoProxy @EnableAspectJAutoProxy},* and {@linkorg.springframework.web.servlet.config.annotation.EnableWebMvc @EnableWebMvc}* for details.** <h2>Constraints when authoring {@code@Configuration} classes</h2>* <ul>*    <li>&#064;Configuration classes must be non-final*    <li>&#064;Configuration classes must be non-local (may not be declared within a method)*    <li>&#064;Configuration classes must have a default/no-arg constructor and may not*        use {@linkAutowired @Autowired} constructor parameters. Any nested configuration classes*        must be {@codestatic}* </ul>**@authorRod Johnson*@authorChris Beams*@since3.0*@seeBean*@seeProfile*@seeImport*@seeImportResource*@seeComponentScan*@seeLazy*@seePropertySource*@seeAnnotationConfigApplicationContext*@seeConfigurationClassPostProcessor*@seeorg.springframework.core.env.Environment*@seeorg.springframework.test.context.ContextConfiguration*/@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Componentpublic @interfaceConfiguration {/*** Explicitly specify the name of the Spring bean definition associated* with this Configuration class.  If left unspecified (the common case),* a bean name will be automatically generated.** <p>The custom name applies only if the Configuration class is picked up via* component scanning or supplied directly to a {@linkAnnotationConfigApplicationContext}.* If the Configuration class is registered as a traditional XML bean definition,* the name/id of the bean element will take precedence.**@returnthe specified bean name, if any*@seeorg.springframework.beans.factory.support.DefaultBeanNameGenerator*/String value()default "";}

spring@PropertySource用法相关推荐

  1. Spring AOP用法

    软件152 杨浩艺 Spring AOP Java web 环境搭建 Java web 项目搭建 Java Spring IOC用法 spring提供了两个核心功能,一个是IoC(控制反转),另外一个 ...

  2. Java Spring IOC用法

    Java Spring IOC用法 Spring IoC 转载于:http://www.cnblogs.com/flowwind/p/4772375.html 在前两篇文章中,我们讲了java web ...

  3. spring RestTemplate用法详解

    spring RestTemplate用法详解 spring 3.2.3 框架参考有说明 21.9 Accessing RESTful services on the Client 转载于:https ...

  4. Spring @Autowired 用法

    Spring @Autowired 用法 首先看下@Component ```举例 1 :``` ```举例 2 :``` 验证是否调用的是默认构造器 ```如何,在启动的时候执行有参数的构造函数?? ...

  5. Spring基本用法1——Spring的核心机制:IOC、DI

            前言:一直想写一个关于Spring的系列文章,但是构思许久却不知道以什么方式阐述,毕竟要把一个复杂框架说清楚并不是那么容易的,我也只能尽力而为了.Spring系列文章打算以这样的顺序展 ...

  6. Spring Boot spring.factories 用法及原理

    文章目录 1. spring.factories 用法 2. spring.factories 实现原理 3. spring.factories 用于解决什么问题? 3.1 业务场景思考及 start ...

  7. java propertysource_[spring] @PropertySource

    配置文件 @PropertySources注解用于加载配置文件到Spring的环境中. 配置文件如下. demo.msg=this is a message. 如何引用到配置文件 在app项目中,我们 ...

  8. spring @Autowired用法

    首先要知道另一个东西,default-autowire,它是在xml文件中进行配置的,可以设置为 byName.byType.constructor 和 autodetect. 比如byName,不用 ...

  9. Spring 事务用法示例与实现原理

    关于事务,简单来说,就是为了保证数据完整性而存在的一种工具,其主要有四大特性:原子性,一致性,隔离性和持久性.对于Spring事务,其最终还是在数据库层面实现的,而Spring只是以一种比较优雅的方式 ...

最新文章

  1. 参加软件测试培训需要学习哪些知识
  2. 分布式事务 GTS 的价值和原理浅析
  3. File类 判断功能和获取功能
  4. apache 提示You don't have permission to access /test.php on this server.怎样解决
  5. Toad 补充与培训 常用菜单
  6. 《Pro/ENGINEER野火版5.0从入门到精通》——2.5 设置零件单位
  7. html如何算小于0判断错误,如果长度小于0在javascript中提醒
  8. 为什么你的店铺不赚钱?
  9. 数据库的数据进行改动,Cognos报表展示未及时更新
  10. Linux_ppc下软件包安装,LINUX2000PPC安装手册
  11. Mac上如何提取解压pkg文件
  12. 介绍几种 Windows10 自带的截图方式
  13. Aliyun 阿里云 机器翻译调用 详解
  14. python websocket实时消息推送
  15. python import random 报错_导致python中import错误的原因是什么
  16. 国外网络需要验证中国手机号码的格式(获取手机的验证码时)(kaggle 收不到手机验证码)
  17. erc20 php,无需gas即可归集ERC20的PHP开发包【SmartWallet】
  18. 微软发函提醒,企业担惊受怕
  19. mysql建表语句非空约束默认_Navicat mysql 建表字段 默认值 空白、NULL 、empty string的区别...
  20. Windows 下 vc++运行库安装,Microsoft Visual C++ Build Tools官方工具

热门文章

  1. 基于ubuntu 的LAMP 优化加固
  2. 成功之路该如何走--工作半年的思考
  3. MySQL批量检查表的脚本
  4. 用RPM包安装MySQL的默认安装路径问题
  5. python学习_19
  6. SSL方式获取邮箱收件箱
  7. $(window).load(function() {})和$(document).ready(function(){})的区别
  8. [IE技巧] 如何让IE 启动的时候不加载任何插件
  9. Linux命令之df
  10. FTP服务器端程序分类