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的更多相关文章

  1. [转] Spring - Java Based Configuration

    PS: Spring boot注解,Configuration是生成一个config对象,@Bean指定对应的函数返回的是Bean对象,相当于XML定义,ConfigurationProperties ...

  2. [转载]Spring Java Based Configuration

    @Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the ...

  3. [转载]Spring Annotation Based Configuration

    Annotation injection is performed before XML injection, thus the latter configuration will override ...

  4. Spring的Java配置方式—@Configuration和@Bean实现Java配置

    Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @BeanSpring的Java配置方式是通过 @Configuration 和 @Be ...

  5. Spring Security Java Config Preview--官方

    原文地址:[1]https://spring.io/blog/2013/07/02/spring-security-java-config-preview-introduction/ [2]https ...

  6. SPRING SECURITY JAVA配置:Web Security

    在前一篇,我已经介绍了Spring Security Java配置,也概括的介绍了一下这个项目方方面面.在这篇文章中,我们来看一看一个简单的基于web security配置的例子.之后我们再来作更多的 ...

  7. Spring 基于Java的Bean声明

    Spring 基于Java的Bean声明 使用@Configuration进行设置: Xml: <?xml version="1.0" encoding="UTF- ...

  8. spring的Java配置入门(Spring Boot学习笔记之一)

    spring的Java配置 1.创建maven项目 使用idea创建maven项目,这里顺便提一下,idea真的比eclipse好用,早点熟悉吧.然后就是maven是java项目管理最主流的工具,自己 ...

  9. SpringBoot学习(二)-->Spring的Java配置方式

    二.Spring的Java配置方式 Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @Bean Spring的Java配置方式是通过 @ ...

随机推荐

  1. Python获取系统音量

    1,如果是windows下 试试这个python 模块winsoundhttp://docs.python.org/2/library/winsound.html这个也可以winmm调整windows ...

  2. Flask的使用2

    1.Flask文件的配置 # 方式一: # 直接书写 app.config['SESSION_COOKIE_NAME'] = 'session_lvning' # 方式二: #引入setting.py ...

  3. angular2项目关于主页结构分析

    这里需要弄清楚两个问题: 一:主页模块如何加载进来 angular2的根模块应用加载之后便会根据根模块路由信息来加载主页模块 export const appRoutes=[ { path:'', r ...

  4. PS文字生成头像

    链接: 教你用PS把文字拼成肖像.... 28个文字组成的肖像画欣赏

  5. receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

    From:https://stackoverflow.com/questions/9626990/receiving-error-error-ssl-error-self-signed-cert-in ...

  6. 解决PuppetDB Failed to submit 'replace facts'问题

    在升级了CentOS6.5后,系统一直运行正常,今天在尝试自动部署了一台新的Bootnode后,发现在运行puppet agent时,发生报错: Error: Could not retrieve c ...

  7. 使用SpringBoot Admin监控SpringCloud微服务

    spring-boot admin的github地址:https://github.com/codecentric/spring-boot-admin 本文基于SpringCloud的环境和配置上增加 ...

  8. Hadoop2.2.0分布式安装配置详解[2/3]

    前言 本文主要通过对hadoop2.2.0集群配置的过程加以梳理,所有的步骤都是通过自己实际测试.文档的结构也是根据自己的实际情况而定,同时也会加入自己在实际过程遇到的问题.搭建环境过程不重要,重要点 ...

  9. 【C#】C#对电子邮件的收发操作

    目录结构: contents structure [+] 简介 发送邮件 读取邮件 1.简介 邮件传输常用的协议有,SMTP.POP3.IMAP4.他们都属于TCP/IP协议,默认状态下分别通过TCP ...

  10. 【java】解析java网络

    目录结构: contents structure [+] 模拟Post与Get请求 设置Authorization头信息 基于TCP的网络编程 TCP协议简介 半关闭的Socket TCP长链接 TC ...