我的来源有一个常数,即第一个字母降低的类名。
是否有Spring实用程序方法将类类型转换为字符串并降低了第一个字母?这允许我安全地重构类名。
例如:
SpringXXX.defaultBeanNameYYY(MyCustomBeanFactoryProcessor.class)
应该产生:
myCustomBeanFactoryProcessor
答案 0 :(得分:3)
默认情况下,形成bean名称的机制称为BeanNameGenerator
(取决于上下文的类型,可能是AnnotationBeanNameGenerator
或DefaultBeanNameGenerator
)。要生成名称,需要bean定义和此定义来自的上下文:
new AnnotationBeanNameGenerator().generateBeanName(definition, context);
例如,您可以在BeanFactoryPostProcessor
子类中编写此处理,其中给出ConfigurableListableBeanFactory
实例:
class MyCustomBeanFactoryProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
String beanName = new AnnotationBeanNameGenerator()
.generateBeanName(new AnnotatedGenericBeanDefinition(MyCustomBeanFactoryProcessor.class),
(BeanDefinitionRegistry) factory);
}
}
最后,如果我们抛弃了Spring所做的上下文和所有检查,我们就可以执行:
Introspector.decapitalize(MyCustomBeanFactoryProcessor.class.getSimpleName());
或
Introspector.decapitalize(ClassUtils.getShortName(MyCustomBeanFactoryProcessor.class));
答案 1 :(得分:1)
你可以这样自己写一个:
public class BeanUtils {
public static String firstToLowerCase(Class clazz) {
String string = clazz.getSimpleName();
String post = string.substring(1, string.length());
String first = ("" + string.charAt(0)).toLowerCase();
return first + post;
}
}
并且这样打电话:BeanUtils.firstToLowerCase(MyCustomBeanFactoryProcessor.class)
答案 2 :(得分:1)
使用getSimpleName
字符串作为 @shi 的提示进行搜索查询我在spring-core/src/main/java/org/springframework/util/ClassUtils.java
中找到了一个这样的实现:
/**
* Return the short string name of a Java class in uncapitalized JavaBeans
* property format. Strips the outer class name in case of an inner class.
* @param clazz the class
* @return the short name rendered in a standard JavaBeans property format
* @see java.beans.Introspector#decapitalize(String)
*/
public static String getShortNameAsProperty(Class<?> clazz) {
String shortName = getShortName(clazz);
int dotIndex = shortName.lastIndexOf(PACKAGE_SEPARATOR);
shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);
return Introspector.decapitalize(shortName);
}
用法:
@Test
public void my() {
String str = org.springframework.util.ClassUtils.getShortNameAsProperty(MyCustomBeanFactoryProcessor.class);
Assert.assertEquals("myCustomBeanFactoryProcessor", str);
}