Spring 3 Java Based Configuration with @Value
Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a trend in the industry to move from XML meta data toward using more annotation driven meta data. I say pick your poison, as one can mess up either.
I do like the readability of using Java code for configuration. Reading the Java classes used for the configuration has a shorter learning curve than reading XML files. Also I can directly unit test my configuration.
The Example
File Highlights
The example code located in on github here. I am using eclipse m2eclipse and spring plugins, and I would recommend importing the project as a maven project.
The Java class used for configuration:
@Configuration
// spring config that loads the properties file
@ImportResource("classpath:/properties-config.xml")
public class AppConfig { /**
* Using property 'EL' syntax to load values from the
* jetProperties value
*/
private @Value("#{jetProperties['jetBean.name']}") String name;
private @Value("#{jetProperties['jetBean.price']}") Long price;
private @Value("#{jetProperties['jetBean.url']}") URL url; /**
* Create a jetBean within the Spring Application Context
* @return a bean
*/
public @Bean(name = "jetBean")
JetBean jetBean() {
JetBean bean = new JetBeanImpl();
bean.setName(name);
bean.setPrice(price);
bean.setUrl(url);
return bean;
} }
The highlights for this class:
- @Configuration – Basic annotation for Java based configuration.
- @ImportResource – Allows us to import a spring xml file to add more functionality to the configuration that this class is building.
- @Value – Creates expression driven dependency injection.
- @Bean – Create a bean managed by the spring container.
The properties-config.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- define the properties file to use -->
<util:properties id="jetProperties"
location="classpath:/jet.properties" />
</beans>
One line that matters. Line number 8. Create a java.util.Properties instance with values loaded from the supplied properties file.
Other files such as the POJO’s and properties files are included in the example. They are very vanilla, so I did not include them in the post. The test case has some changes in it.
public class JetBeanTest {
@Test
public void testJetBean() {
// create the spring container using the AppConfig
// @Configuration class
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
JetBean jetBean = ctx.getBean(JetBean.class);
assertThat(jetBean.getName(), equalTo("Gulf Stream G550"));
assertThat(jetBean.getPrice(), equalTo(Long.valueOf(60000000)));
URL gulfstream;
try {
gulfstream =
new URL("http://www.gulfstream.com/products/g550/");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
fail("error creating URL");
throw new RuntimeException("error creating URL");
}
assertThat(jetBean.getUrl(), equalTo(gulfstream));
}
}
The main change is the new class AnnotationConfigApplicationContext which drives the creation of the Spring application context via Java configuration.
Recap
Use @Configuration to annotate your configuration class. Mark your beans with @Bean. The following annotations are supported:
- @Configuration
- @Bean
- @DependsOn
- @Primary
- @Lazy
- @Import
- @ImportResource
- @Value
Using @Value with Spring Expression Language
Now starts the crazy cool stuff. The @Value can be used on fields, methods and parameters. Plus, Spring Expression Language (SpEL) defines the ‘value’ through the syntax #{ < SpEL expression > }. The syntax can get a bit harry, but is incredibly powerful. In this example I have used SpEL to load values from the javaProperties java.lang.Properties Object with syntax like:
// jetProperties java.lang.Properties bean in context.
// jetBean.name value in the property file
@Value("#{jetProperties['jetBean.name']}") String name
Using @Value and SpEL gives you the functionality to do such things as: setting default values, accessing system level properties, logical operators, regex, mathematical operations.
To summarize as Uncle Ben said:
With great power there must come great responsibility.
Link to the example code located in on github here.
Much thanks to Chris Beams and his blog post on Springsource.
转自:http://chrislovecnm.com/2010/03/08/spring-3-java-based-configuration-with-value/
Spring 3 Java Based Configuration with @Value的更多相关文章
- [转] Spring - Java Based Configuration
PS: Spring boot注解,Configuration是生成一个config对象,@Bean指定对应的函数返回的是Bean对象,相当于XML定义,ConfigurationProperties ...
- [转载]Spring Java Based Configuration
@Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the ...
- [转载]Spring Annotation Based Configuration
Annotation injection is performed before XML injection, thus the latter configuration will override ...
- Spring的Java配置方式—@Configuration和@Bean实现Java配置
Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @BeanSpring的Java配置方式是通过 @Configuration 和 @Be ...
- Spring Security Java Config Preview--官方
原文地址:[1]https://spring.io/blog/2013/07/02/spring-security-java-config-preview-introduction/ [2]https ...
- SPRING SECURITY JAVA配置:Web Security
在前一篇,我已经介绍了Spring Security Java配置,也概括的介绍了一下这个项目方方面面.在这篇文章中,我们来看一看一个简单的基于web security配置的例子.之后我们再来作更多的 ...
- Spring 基于Java的Bean声明
Spring 基于Java的Bean声明 使用@Configuration进行设置: Xml: <?xml version="1.0" encoding="UTF- ...
- spring的Java配置入门(Spring Boot学习笔记之一)
spring的Java配置 1.创建maven项目 使用idea创建maven项目,这里顺便提一下,idea真的比eclipse好用,早点熟悉吧.然后就是maven是java项目管理最主流的工具,自己 ...
- SpringBoot学习(二)-->Spring的Java配置方式
二.Spring的Java配置方式 Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @Bean Spring的Java配置方式是通过 @ ...
随机推荐
- j2me必备之网络开发数据处理
第9章 无线网络开发MIDP提供了一组通用的网络开发接口,用来针对不同的无线网络应用可以采取不同的开发接口.基于CLDC的网络支持是由统一网络连接框架(Generic Connection Frame ...
- U3D面试五
U3D面试题 配置Unity3D调试环境 Visual Studio Tools for Unity 访问http://unityvs.com 安装对应的版本 使用方法(生成项目文件,如何调试) Ar ...
- How determine the RC time constant in PWM DAC low-pass filter?
how determine the RC time constant in PWM digital to analog low-pass filter? I 'm looking for the be ...
- Xshell配置ssh免密码登录-密钥公钥(Public key)与私钥(Private Key)登录【已成功实例】
本文转自https://blog.csdn.net/qjc_501165091/article/details/51278696 ssh登录提供两种认证方式:口令(密码)认证方式和密钥认证方式.其中口 ...
- Docker修改daemon.json后无法启动的问题
本文的运行环境为Centos 7.3,Docker与Kubernetes的安装方式见kubeadm安装kubernetes V1.11.1 集群 最近在整理Docker和Kubernetes中的日志与 ...
- OpenCV支持向量机(SVM)介绍
支持向量机(SVM)介绍 目标 本文档尝试解答如下问题: 如何使用OpenCV函数 CvSVM::train 训练一个SVM分类器, 以及用 CvSVM::predict 测试训练结果. 什么是支持向 ...
- CDH:cdh5环境mkdir: Permission denied: user=root, access=WRITE, inode="/user":hdfs:hadoop:drwxr-xr-x
产生问题原因: 环境hadoop2,cdh5创建 使用hadoop fs -mdkir /use/xxx创建文件路径时,出现权限问题 前提我们已经把当前用户zhangsan和root放到/etc/su ...
- ORA-16447 Redo apply was not active at the target standby database
Cause ALTER SYSTEM FLUSH REDO TO STANDBY failed because redo apply is not active at the target datab ...
- CentOS7下 让Docker pull命令使用squid做http代理拉取目标镜像仓库的镜像
场景,如下图所示: 服务器B具有两个网卡,分别和服务器A和服务器C互通,这里想要在服务器C上借助服务器B作为桥梁,拉取镜像仓库服务器A上的镜像. 思路也很简单,在服务器上搭建HTTP代理服务,服务器C ...
- C语言100个经典的算法
C语言的学习要从基础開始.这里是100个经典的算法-1C语言的学习要从基础開始,这里是100个经典的算法 题目:古典问题:有一对兔子,从出生后第3个月起每一个月都生一对兔子.小兔 子长到第三个月后每一 ...