商讯信箱
用户名: @
密  码:   注册|忘记密码
登录
个人用户经销商
您的位置:首页 > 技术频道 > 正文

    2. HelloWorld with JavaConfig
    2.1 获得JavaConfig
    JavaConfig的下载地址:
    http://downloads.sourceforge.net/springframework/spring-javaconfig-1.0-m2-with-dependencies.zip?modtime=1178633399&big_mirror=0
    关于JavaConfig的更多信息请访问:
    http://www.springframework.org/node/455

    2.2 HelloWorld程序
    我们将以HelloWorld程序来开始JavaConfig之旅!
    HelloWorld.java
package com.springconfig.example.bean; public class HelloWorld { private String word; public void sayHello() { System.out.println(this.word); } public void setWord(String word) { this.word = word; } }
    HelloWorld.java是一个非常简单的java类。只有两个方法:
    setWord()设置私有变量word的值。
    SayHello()打印出word的值

    现在我们以JavaConfig来描述HellWorld这个Bean,而不是以xml方式描述。
    我们需要创建一个管理类,并加上适当的注释就可以了。

package com.springconfig.example.chapter2; @Configuration public class HelloWorldConfiguration { @Bean public HelloWorld helloWorld(){ HelloWorld helloWorldBean = new HelloWorld(); helloWorldBean.setWord("Hello world!"); return helloWorldBean; } }
    上面的代码,我们创建了一个叫HelloWorldConfiguration的类,并加上了一个类级别的注释@Configuration.
这个类中,只有一个helloWorld()的方法,返回类型为HelloWorld。这个方法,首先会创建一个HelloWorld的实例,这个实例设置word属性为"Hello world!",然后返回这个实例。
    这个方法有一个方法级别的注释@Bean看起来,这个与普通的java类并没有什么不一样。但是这是一个非常简单的avaConfig实现。
    如果把HelloWorld用xml来描述,等价于:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="helloWorld" class="com.springconfig.example.bean.HelloWorld"> <property name="word"> <value>Hello world!</value> </property> </bean> </beans>
    JavaConfig的使用也非常的简单
    HelloWorldWithJavaConfig.java
package com.springconfig.example.chapter2; public class HelloWorldWithJavaConfig { public static void main(String[] args){ ApplicationContext config = new AnnotationApplicationContext(HelloWorldConfiguration.class.getName()); HelloWorld helloWorld = (HelloWorld)config.getBean("helloWorld"); helloWorld.sayHello(); } }
    程序运行后的输出结果如下:
    Hello world!

    可见JavaConfig的使用与XML一样简单,只是这里AnootationApplicationcontext替代了ClassPathXmlApplicationContext. 

    再来看看HelloWorldConfiguration类。
    加上@Configuration注释后的HelloWorldConfiguration类就像一个描述Bean配置的XML文件。
    加上@Bean注释后的helloWorld()方法就是一个Bean描述。Bean的ID为helloWorld.而Bean的class属性为    com.springconfig.example.bean.HelloWorld. 并为这个Bean的word属性注入了值Hello world!
1 2 3 4 5 6 7 8 9 10 11 12
【内容导航】
第1页: 第1页 第2页: 第2页
第3页: 第3页 第4页: 第4页
第5页: 第5页 第6页: 第6页
第7页: 第7页 第8页: 第8页
第9页: 第9页 第10页: 第10页
第11页: 第11页 第12页: 第12页
©版权所有。未经许可,不得转载。
[责任编辑:赵恒]