简体   繁体   中英

How do I prefix each bean id in a package (inc. sub-packages) with a constant string in Spring?

Is there a way to prefix each bean annotated with @Component in a certain package and subpackages with a given string?

Say, we have this bean, for example:

package com.example.foo;

@Component
class MyBean {}

I want all beans in foo to be prefixed with foo , so that the automatically (by component scan) generated bean id is either fooMyBean (preferred, with capital 'M') or foo-myBean (instead of the default myBean ). (The prefix being a String defined somewhere, not being automatically derived from the package name.)

Alternatively, can I achieve this by using custom annotations, like @FooComponent , say? (How? ;-) )

Spring uses a BeanNameGenerator strategy to generate bean names. In particular, the AnnotationBeanNameGenerator is the one which generates names for @Component classes with the first-letter-lower-cased strategy.

You could implement your own BeanNameGenerator and apply a custom strategy by inspecting the passed BeanDefinition .

If you're using Spring Boot, this can be done right in the SpringApplicationBuilder .

@SpringBootApplication
public class DemoApplication {

    public static class CustomGenerator extends AnnotationBeanNameGenerator {

        @Override
        public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
            /**
              * access bean annotations or package ...
              */
            return super.generateBeanName(definition, registry);
        }
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(DemoApplication.class)
                .beanNameGenerator(new CustomGenerator())
                .run(args);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM