标签:name bean value Bean ArticleService 2.3 articleService
戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
[查看视频教程]
源码:
1 @org.springframework.core.annotation.AliasFor("name") 2 java.lang.String[] value() default {}; 3 4 @org.springframework.core.annotation.AliasFor("value") 5 java.lang.String[] name() default {};
@Bean中的name和value属性 和 配置文件中的bean标签的name属性有同样的功能。
@Bean配置的类的默认id是方法的名称,但是我们可以通过value或者name给这个bean取别名。
注意:value和name属性不能并存。 而且如果配置了value或者name,那么我们将无法在通过方法名称获取这个bean了。
例如:
1 //配置ArticleService对象 2 @Bean(value="aservice") 3 //@Bean(name="aservice") 4 public ArticleService articleService(){ 5 ArticleService articleService = new ArticleService(); 6 //注入对应的属性 7 articleService.setArticleDAO(articleDAO()); 8 articleService.setAutorDAO(authorDAO()); 9 return articleService; 10 }
我们可以通过下面的方式获取service对象:
通过类型获取:
1 ArticleService bean = ac.getBean(ArticleService.class);
通过方法名称获取:
如果配置了value或者name,那么下面的操作会失效
1 ArticleService bean = (ArticleService) ac.getBean("articleService");
通过别名获取:
value和name配置别名,但是两个属性不能共存,也不能使用特殊符号,也不能同时配置多个别名
1 ArticleService bean = (ArticleService) ac.getBean("aservice");
标签:name,bean,value,Bean,ArticleService,2.3,articleService 来源: https://www.cnblogs.com/jiafa/p/13776311.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。