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

    3.3 @ExternalBean
    指定Bean是一个外部Bean
    示例:
@Configuration public abstract class ExternalConfiguration { @ExternalBean public abstract HelloWorld helloWorld(); } public class ConfigurationWithExternal { public static void main(String[] args){ ApplicationContext context = new AnnotationApplicationContext(ConfigurationFull.class.getName(),ExternalConfiguration.class.getName()); HelloWorld hello = (HelloWorld)context.getBean("helloWorld"); hello.sayHello(); } }
    这里,在ExternalConfiguration中定义的helloWorld自动会被,在ConfigurationFull中定义的helloWorld覆盖。
    所以,@ExtenalBean的意思是,这个是在父Context中定义的,这个父context可以是一个Configuration或是一个外部的xml文件。使用这个注释的好处是为了保持重构友好。

    3.4 @ScopedProxy
    Spring通过scoped proxies提供了一个方便的作用域依赖的处理方法。最简单的方式就是创建一个代理。在当使用xml配置时,使用<aop:scoped-proxies/>元素。JavaConfig提供了一个等价物就是@ScopedProxy,它提供了<aop:scoped-proxies/>相同的语义和配置选项。
@Bean(scope = DefaultScopes.SESSION) @ScopedProxy public UserPreferences userPreferences() { return new UserPreferences(); } @Bean public Service userService() { UserService service = new SimpleUserService(); // a reference to the proxied 'userPreferences' bean service.seUserPreferences(userPreferences()); return service; }
    一个userPreferences的Bean定义了Session的作用域,一个为singleton作用域的Bean userService注入了这个bean userPreferences.因为userSerivce只会被实例化一次,理论上它只会操纵一个userPreferences对象。而我们是希望它每次去从session中取回一个userPreferences对象。所以这就需要一个代理。这个代理总会在我们需要使用userPreferences对象时,自动去从session中取回userPreferences对象。
    <aop:scoped-proxies/>及@ScopedProxy就是提供了这样的功能。
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页
©版权所有。未经许可,不得转载。
[责任编辑:赵恒]