测试例子

package com.hjzgg.auth.config;

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;
import org.springframework.util.StringUtils; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List; /**
* Created by hujunzheng on 2017/6/22.
*/
@Configuration
@PropertySource("classpath:conf/config.properties")
public class SystemConfig { public static class User {
public static String NAME;
public static int AGE;
public static int USER_ID;
public static String ADDRESS;
} @Autowired
private Environment env; @Bean
public SystemConfig oauthSystemConfig() throws IllegalAccessException {
setStaticPropertiesValue(SystemConfig.class);
Class<?>[] clazzs = SystemConfig.class.getClasses();
for (Class clazz: clazzs) {
setStaticPropertiesValue(clazz);
}
return null;
} private void setStaticPropertiesValue(Class<?> clazz) throws IllegalAccessException {
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(new String[] {}));
} 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源码说明

package org.springframework.context.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; /**
* Indicates that a class declares one or more {@link Bean @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">
* @Configuration
* public class AppConfig {
* @Bean
* public MyBean myBean() {
* // instantiate, configure and return bean ...
* }
* }</pre>
*
* <h2>Bootstrapping {@code @Configuration} classes</h2>
* <h3>Via {@code AnnotationConfigApplicationContext}</h3>
* {@code @Configuration} classes are typically bootstrapped using either
* {@link AnnotationConfigApplicationContext} or its web-capable variant,
* {@link org.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 {@link AnnotationConfigApplicationContext} Javadoc for further details and see
* {@link org.springframework.web.context.support.AnnotationConfigWebApplicationContext
* AnnotationConfigWebApplicationContext} for {@code web.xml} configuration instructions.
*
* <h3>Via Spring {@code <beans>} XML</h3>
* <p>As an alternative to registering {@code @Configuration} classes directly against an
* {@code AnnotationConfigApplicationContext}, {@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 {@link ConfigurationClassPostProcessor} and other annotation-related
* post processors that facilitate handling {@code @Configuration} classes.
*
* <h3>Via component scanning</h3>
* <p>{@code @Configuration} is meta-annotated with {@link Component @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 {@link Autowired @Autowired}/{@link javax.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 {@link ComponentScan @ComponentScan} annotation:
* <pre class="code">
* @Configuration
* @ComponentScan("com.acme.app.services")
* public class AppConfig {
* // various @Bean definitions ...
* }</pre>
*
* See {@link ComponentScan @ComponentScan} Javadoc for details.
*
*
* <h2>Working with externalized values</h2>
* <h3>Using the {@code Environment} API</h3>
* Externalized values may be looked up by injecting the Spring
* {@link org.springframework.core.env.Environment Environment} into a
* {@code @Configuration} class using the {@code @Autowired} or the {@code @Inject}
* annotation:
* <pre class="code">
* @Configuration
* public class AppConfig {
* &#064Inject Environment env;
*
* @Bean
* public MyBean myBean() {
* MyBean myBean = new MyBean();
* myBean.setName(env.getProperty("bean.name"));
* return myBean;
* }
* }</pre>
*
* Properties resolved through the {@code Environment} reside in one or more "property
* source" objects, and {@code @Configuration} classes may contribute property sources to
* the {@code Environment} object using
* the {@link org.springframework.core.env.PropertySources @PropertySources} annotation:
* <pre class="code">
* @Configuration
* @PropertySource("classpath:/com/acme/app.properties")
* public class AppConfig {
* &#064Inject Environment env;
*
* @Bean
* public MyBean myBean() {
* return new MyBean(env.getProperty("bean.name"));
* }
* }</pre>
*
* See {@link org.springframework.core.env.Environment Environment}
* and {@link PropertySource @PropertySource} Javadoc for further details.
*
* <h3>Using the {@code @Value} annotation</h3>
* Externalized values may be 'wired into' {@code @Configuration} classes using
* the {@link Value @Value} annotation:
* <pre class="code">
* @Configuration
* @PropertySource("classpath:/com/acme/app.properties")
* public class AppConfig {
* &#064Value("${bean.name}") String beanName;
*
* @Bean
* public MyBean myBean() {
* return new MyBean(beanName);
* }
* }</pre>
*
* This approach is most useful when using Spring's
* {@link org.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 {@link Value @Value} Javadoc, and see {@link Bean @Bean} Javadoc for details on working with
* {@code BeanFactoryPostProcessor} types such as
* {@code PropertySourcesPlaceholderConfigurer}.
*
* <h2>Composing {@code @Configuration} classes</h2>
* <h3>With the {@code @Import} annotation</h3>
* <p>{@code @Configuration} classes may be composed using the {@link Import @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">
* @Configuration
* public class DatabaseConfig {
* @Bean
* public DataSource dataSource() {
* // instantiate, configure and return DataSource
* }
* }
*
* @Configuration
* @Import(DatabaseConfig.class)
* public class AppConfig {
* &#064Inject DatabaseConfig dataConfig;
*
* @Bean
* public MyBean myBean() {
* // reference the dataSource() bean method
* return new MyBean(dataConfig.dataSource());
* }
* }</pre>
*
* Now both {@code AppConfig} and the imported {@code DatabaseConfig} can be bootstrapped
* by registering only {@code AppConfig} 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 {@link Profile @Profile} annotation to
* indicate they should be processed only if a given profile or profiles are
* <em>active</em>:
* <pre class="code">
* @Profile("embedded")
* @Configuration
* public class EmbeddedDatabaseConfig {
* @Bean
* public DataSource dataSource() {
* // instantiate, configure and return embedded DataSource
* }
* }
*
* @Profile("production")
* @Configuration
* public class ProductionDatabaseConfig {
* @Bean
* public DataSource dataSource() {
* // instantiate, configure and return production DataSource
* }
* }</pre>
*
* See {@link Profile @Profile} and {@link org.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 {@link ImportResource @ImportResource} annotation. Bean definitions imported from XML can be
* injected using {@code @Autowired} or {@code @Import}:
* <pre class="code">
* @Configuration
* @ImportResource("classpath:/com/acme/database-config.xml")
* public class AppConfig {
* &#064Inject DataSource dataSource; // from XML
*
* @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">
* @Configuration
* public class AppConfig {
* @Inject DataSource dataSource;
*
* @Bean
* public MyBean myBean() {
* return new MyBean(dataSource);
* }
*
* @Configuration
* static class DatabaseConfig {
* @Bean
* DataSource dataSource() {
* return new EmbeddedDatabaseBuilder().build();
* }
* }
* }</pre>
*
* When bootstrapping such an arrangement, only {@code AppConfig} need be registered
* against the application context. By virtue of being a nested {@code @Configuration}
* class, {@code DatabaseConfig} <em>will be registered automatically</em>. This avoids
* the need to use an {@code @Import} annotation when the relationship between
* {@code AppConfig} {@code DatabaseConfig} 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 {@link Lazy @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 {@code spring-test} module
* provides the {@code @ContextConfiguration} annotation, which as of Spring 3.1 can
* accept an array of {@code @Configuration} {@code Class} objects:
* <pre class="code">
* @RunWith(SpringJUnit4ClassRunner.class)
* @ContextConfiguration(classes={AppConfig.class, DatabaseConfig.class})
* public class MyTests {
*
* @Autowired MyBean myBean;
*
* @Autowired DataSource dataSource;
*
* @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
* {@link org.springframework.scheduling.annotation.EnableAsync @EnableAsync},
* {@link org.springframework.scheduling.annotation.EnableScheduling @EnableScheduling},
* {@link org.springframework.transaction.annotation.EnableTransactionManagement @EnableTransactionManagement},
* {@link org.springframework.context.annotation.EnableAspectJAutoProxy @EnableAspectJAutoProxy},
* and {@link org.springframework.web.servlet.config.annotation.EnableWebMvc @EnableWebMvc}
* for details.
*
* <h2>Constraints when authoring {@code @Configuration} classes</h2>
* <ul>
* <li>@Configuration classes must be non-final
* <li>@Configuration classes must be non-local (may not be declared within a method)
* <li>@Configuration classes must have a default/no-arg constructor and may not
* use {@link Autowired @Autowired} constructor parameters. Any nested configuration classes
* must be {@code static}
* </ul>
*
* @author Rod Johnson
* @author Chris Beams
* @since 3.0
* @see Bean
* @see Profile
* @see Import
* @see ImportResource
* @see ComponentScan
* @see Lazy
* @see PropertySource
* @see AnnotationConfigApplicationContext
* @see ConfigurationClassPostProcessor
* @see org.springframework.core.env.Environment
* @see org.springframework.test.context.ContextConfiguration
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration { /**
* 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 {@link AnnotationConfigApplicationContext}.
* If the Configuration class is registered as a traditional XML bean definition,
* the name/id of the bean element will take precedence.
*
* @return the specified bean name, if any
* @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
*/
String value() default ""; }

spring@PropertySource用法的更多相关文章

  1. Java Spring AOP用法

    Java Spring AOP用法 Spring AOP Java web 环境搭建 Java web 项目搭建 Java Spring IOC用法 spring提供了两个核心功能,一个是IoC(控制 ...

  2. Java Spring IOC用法

    Java Spring IOC用法 Spring IoC 在前两篇文章中,我们讲了java web环境搭建 和 java web项目搭建,现在看下spring ioc在java中的运用,开发工具为In ...

  3. Spring JdbcTemplate用法整理

    Spring JdbcTemplate用法整理: xml: <?xml version="1.0" encoding="UTF-8"?> <b ...

  4. spring RestTemplate用法详解

    spring RestTemplate用法详解 spring 3.2.3 框架参考有说明 21.9 Accessing RESTful services on the Client

  5. SpringBoot系列之@PropertySource用法简介

    SpringBoot系列之@PropertySource用法简介 继上篇博客:SpringBoot系列之@Value和@ConfigurationProperties用法对比之后,本博客继续介绍一下@ ...

  6. Spring Aspect 用法略讲

    『配置Aspect』 若要启用AspectJ风格的注解则必须额外的导入AspectJ的jar包,此外还需要在spring的配置文件中进行配置,配置方式有两种; 一.在配置文件的Schema中进行配置 ...

  7. Spring @Value 用法小结,#与$的区别

    20161016更新:这货其实是SpEL的功能,来这里看看吧: Spring 4 官方文档学习(五)核心技术之SpEL 起因 一直的用法是 @Value("${jdbc.driverClas ...

  8. spring assert 用法

    spring在提供一个强大的应用开发框架的同时也提供了很多优秀的开发工具类,合理的运用这些工具,将有助于提高开发效率.增强代码质量.下面就最常用的Assert工具类,简要介绍一下它的用法.Assert ...

  9. Spring @RequestHeader用法

    Spring MVC提供了 @RequestHeader注解,能够将请求头中的变量值映射到控制器的参数中.下面是一个简单的例子: import org.springframework.stereoty ...

随机推荐

  1. LOJ#2983. 「WC2019」数树

    传送门 抄题解 \(Task0\),随便做一下,设 \(cnt\) 为相同的边的个数,输出 \(y^{n-cnt}\) \(Task1\),给定其中一棵树 设初始答案为 \(y^n\),首先可以发现, ...

  2. 个推数据统计产品(个数)iOS集成实践

    最近业务方给我们部门提了新的需求,希望能一站式统计APP的几项重要数据.这次我们尝试使用的是个推(之前专门做消息推送的)旗下新推出的产品“个数·应用统计”,根据官方的说法,个推的数据统计产品通过专业的 ...

  3. Java基础-处理json字符串解析案例

    Java基础-处理json字符串解析案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible ...

  4. Python模块调用方式详解

    Python模块调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其 ...

  5. poj 3686 Priest John's Busiest Day

    http://poj.org/problem?id=3683 2-sat 问题判定,输出一组可行解 http://www.cnblogs.com/TheRoadToTheGold/p/8436948. ...

  6. PythonCharm 配置本地反向代理激活

    以下方法仅做学习使用,如果条件允许,请自行购买正版软件,做开发的都知道软件开发出来不容易,能够支持就支持正版吧 首先去官网 下载 自己需要的 PYCHARM 版本 安装完启动会提示要激活, 选择 li ...

  7. Spring Cloud(十四)Config 配置中心与客户端的使用与详细

    前言 在上一篇 文章 中我们直接用了本应在本文中配置的Config Server,对Config也有了一个基本的认识,即 Spring Cloud Config 是一种用来动态获取Git.SVN.本地 ...

  8. 20155202 2016-2017-2 《Java程序设计》第5周学习总结

    20155202 2016-2017-2 <Java程序设计>第5周学习总结 教材学习内容总结 第八章:异常处理 java中所有错误会包装成对象,可以尝试(try)执行程序并捕捉(catc ...

  9. C语言字节对齐 __align(),__attribute((aligned (n))),#pragma pack(n)【转】

    转自:https://www.cnblogs.com/ransn/p/5081198.html 转载地址 : http://blog.csdn.net/21aspnet/article/details ...

  10. linux C守护进程编写

    linux编程-守护进程编写 守护进程(Daemon)是运行在后台的一种特殊进程.它独立于控制终端并且周期性地执行某种任务或等待 处理某些发生的事件.守护进程是一种很有用的进程. Linux的大多数服 ...