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

    7. Bean的命名策略
    使用JavaConfig由方法产生的Bean,其方法名就是Bean名称。但是当多个方法重名,或者有多个Congiguration或与外部xml混用时,这种方式并不合适。不同的类全覆盖彼此的定义。为了自定义bean名称产生的行为,可以能过实现BeanNamingStrategy 接口来提供它自己的bean名称产生策略

    BenaNamingStrategy有一个默认的实现MethodNameStrategy

    MethodNameStrategy提供了一个prefix属性,用于指定Bean的前辍的产生方式
    Prefix有三个取值。
    NONE:即没有前辍,仍然使用方法名作为Bean的名称。
    CLASS:使用类名称为作Bean的前辍,中间以.号相连。如:ConfigurationFull.word
    FQN:使用完整的类路径作为Bean的前辍。如:com.springconfig.example.chapter3.ConfigurationFull.word

    下面就这三种方式进行说明:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean class="com.springconfig.example.chapter3.ConfigurationFull"> </bean> <bean class="org.springframework.config.java.process.ConfigurationPostProcessor"> <property name="namingStrategy"> <bean class="org.springframework.config.java.naming.MethodNameStrategy"> <property name="prefix" value="CLASS"/> </bean> </property> </bean> </beans> public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("com/springconfig/example/chapter3/applicationContext.xml"); String word = (String)context.getBean("ConfigurationFull.word"); System.out.println(word); } }

    程序输出:
    HelloWorld!

    把上面的prefix属性值换成FQN

public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("com/springconfig/example/chapter3/applicationContext.xml"); String word = (String)context.getBean("com.springconfig.example.chapter3.ConfigurationFull.word"); System.out.println(word); } }
    程序输出:
    HelloWorld!
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页
©版权所有。未经许可,不得转载。
[责任编辑:赵恒]