Assuming you're already using the component classpath scanning, then you can give an explicit name to the component, rather than letting Spring auto-generate a name for you:
@Service("myService")
public class MyService {
...
}
I haven't tested this, but I believe this is the case.
edit: After a bit of digging, the logic for determining the bean name is found in AnnotationBeanNameGenerator.generateBeanName()
.:
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
if (definition instanceof AnnotatedBeanDefinition) {
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
if (StringUtils.hasText(beanName)) {
// Explicit bean name found.
return beanName;
}
}
// Fallback: generate a unique default bean name.
return buildDefaultBeanName(definition);
}
In other words, it tries to get an explicit bean name from the annotation(s), and failing that, it uses the default:
protected String buildDefaultBeanName(BeanDefinition definition) {
String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());
return Introspector.decapitalize(shortClassName);
}
So yes, for an annotated class called MyService
, the auto-generated bean name should indeed be myService
, so your code should work.
Out of curiosity, what happens when you use @Component
instead of @Service
?