自动分配spring的bean名称以防止名称冲突? [英] Automatically assign spring's bean name to prevent name conflicts?

查看:598
本文介绍了自动分配spring的bean名称以防止名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在spring应用程序中,如果两个程序员开发两个包,将@Repository注释为相同的类名,则Spring会抛出"IllegalStateException":

In a spring app , if two programmers develop two packages , annotating @Repository to the same class name , Spring will throw "IllegalStateException" :

注释指定的Bean名称 'mybean'用于bean类 [foobar.package1.mybean]冲突 与现有的,不兼容的bean 相同名称和类别的定义 [foobar.package2.mybean]

Annotation-specified bean name 'mybean' for bean class [foobar.package1.mybean] conflicts with existing, non-compatible bean definition of same name and class [foobar.package2.mybean]

一种解决方案是在@Repository中添加额外的值,例如@Repository("package1.mybean")@Repository("package2.mybean"),但是我正在寻找一种更有效的解决方案,该解决方案可以自动缓解这种情况.我希望该解决方案可以实现这些目标:

One solution is to add extra value in the @Repository , such as @Repository("package1.mybean") and @Repository("package2.mybean") , but I am looking for a more efficient solution , that can automatically ease such situation . I hope the solution can achieve these goals :

  1. 程序员可以在其程序包中随意命名其bean className,而不管其名称是否与其他程序包(程序员)冲突.这样程序员就不必大喊嘿,我将使用Bean名称XXXXX,不要与我冲突".

  1. Programmers could arbitrarily name their bean className in his package , regardless of name conflicting with other packages(programmers). So that programmer doesn't need to yell 'Hey , I am going to use bean name XXXXX , don't conflict with me'.

没有手动分配XML Bean名称.

No manually XML bean name assign.

有什么想法吗?谢谢. (春季3)

Any ideas ? Thanks. (Spring 3)

推荐答案

在配置中的某些地方,您已经启用了类路径扫描,可能使用了

Somewhere in your config, you've enabled classpath scanning, probably using

<context:component-scan>

您可以指定一个名为name-generator的属性,该属性采用实现BeanNameGenerator接口的bean.创建您自己的接口实现,并提供对其的引用.

You can specify a property called name-generator, which takes a bean that implements the BeanNameGenerator interface. Create your own implementation of that interface and provide a reference to it.

这篇关于自动分配spring的bean名称以防止名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆