• 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/

  • 相关阅读:
    Android Watchdog
    Android Zygote进程是如何fork一个APP进程的
    java多线程面试题小结
    Java Socket通信以及可能出现的问题解决
    Java对象的浅拷贝和深拷贝&&String类型的赋值
    AtomicLong和LongAdder的区别
    JDK中Concurrent包介绍及使用(包含atomic包/lock包/并发容器/执行器)
    final关键字总结
    Java内存模型-final域的内存语义--没明白,预留以后继续理解
    synchronized底层实现原理&CAS操作&偏向锁、轻量级锁,重量级锁、自旋锁、自适应自旋锁、锁消除、锁粗化
  • 原文地址:https://www.cnblogs.com/younggun/p/3425755.html
Copyright © 2020-2023  润新知