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

    在Configuration中访问Factory

    有时需要在Configuration类中获得Factory对象,可以继承ConfigurationSupport。

package com.springconfig.example.chapter3; @Configuration public class ConfigurationWithSupport extends ConfigurationSupport{ @Bean public String sayWord(){ String word = (String)getBean("word"); return word; } }
    在sayWord方法中,是能过getBean方法来获得一个名为word的Bean,并返回这个Bean的值。

public static void main(String[] args){ ApplicationContext context = new AnnotationApplicationContext(ConfigurationFull.class.getName(),ConfigurationWithSupport.class.getName()); String word = (String)context.getBean("sayWord"); System.out.println(word); }
    3.2 @Bean
    @Bean用来在Configuration中指定一个Bean定义。方法名就是Bean名称。当然你也可以使用aliases元素来为bean取一个别名。

@Bean public HelloWorld helloWorld(){ HelloWorld helloWorld = new HelloWorld(); helloWorld.setWord(word()); return helloWorld; }
    例如:上面的例子,spring就像创造一个名称叫helloWorld的bean。返回值为HelloWorld类型的实例。
    @Bean 是一个方法级的注释,用java代码来创建和装配一个Bean实列。它相当于<bean/>标签,并可以支持xml的<bean/>标签提供的大部分选项,如:autowiring,lazy-init,dependency-check,depends-on,scope等。

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页
©版权所有。未经许可,不得转载。
[责任编辑:赵恒]