Spring 3 Java Based Configuration with @Value
2013-11-15 17:07
295 查看
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 Java class used for configuration:
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:
One line that matters. Line number 8. Create a
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.
The main change is the new class
@Configuration
@Bean
@DependsOn
@Primary
@Lazy
@Import
@ImportResource
@Value
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/
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.Propertiesinstance 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
AnnotationConfigApplicationContextwhich drives the creation of the Spring application context via Java configuration.
Recap
Use@Configurationto 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@Valuecan 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.PropertiesObject 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/
相关文章推荐
- Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException
- [转载]Spring Java Based Configuration
- Spring AOP Advices - Before advice example - xml based configuration - See more at: http://www.java2
- Spring学习(13)--- 基于Java类的配置Bean 之 @Configuration & @Bean注解
- run scala with java use spring mvc(java项目加入 scala)
- Grassroots Groovy: Configuration with ConfigSlurper JAVA读取groovy配置文件(Config.groovy)
- Spring AOP Advices - After returning advice example - xml based configuration
- AS出现 Process 'command 'F:\java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1问题
- Process 'command 'C:\Program Files\Java\jdk1.8.0_11\bin\java.exe'' finished with non-zero exit value
- springboot错误 java.lang.IllegalArgumentException:No converter found for return value of type
- 用Java进行基于浏览器的桌面应用程序开发(Browser-based desktop application development with java)
- Spring SpEL in JSP and Assign SpEL value to Java variable in JSP
- 刚用SpringBoot搭建的项目,To display the auto-configuration report re-run your application with 'debug' enab
- Android开发常见问题之Process 'command 'D:\Java Jdk\java\bin\java.exe'' finished with non-zero exit value 2
- Mybatis Spring multiple databases Java configuration
- Beyond REST: How to build a HATEOAS API in Java with Spring MVC, Jersey (JAX-RS) and VRaptor
- 【JAVA笔记——器】Spring面向切面编程 Aspect Oriented Programming with Spring
- How to check “hasRole” in Java Code with Spring Security?
- Hashtable and HashMap are two hash based collection in Java and used to store objects as key value p
- [Android fix] java.exe finished with non-zero exit value 2