在Spring中,如何在一个包(包括子包)中的每个bean id前面加上一个常量字符串? [英] How do I prefix each bean id in a package (inc. sub-packages) with a constant string in Spring?

查看:232
本文介绍了在Spring中,如何在一个包(包括子包)中的每个bean id前面加上一个常量字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在特定的程序包和子程序包中,是否有给每个带有@Component注释的bean的前缀,并带有给定的字符串?

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

说,例如,我们有这个bean:

Say, we have this bean, for example:

package com.example.foo;

@Component
class MyBean {}

我希望foo中的所有bean都以foo作为前缀,以便自动(通过组件扫描)生成的bean id是fooMyBean(首选,大写'M')或foo-myBean(而不是默认的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.)

或者,我可以通过使用自定义注释(例如@FooComponent)来实现此目的吗? (如何?;-))

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

推荐答案

Spring使用

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.

您可以实现自己的BeanNameGenerator并通过检查传递的BeanDefinition来应用自定义策略.

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

如果您使用的是Spring Boot,则可以直接在

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);
    }
}

这篇关于在Spring中,如何在一个包(包括子包)中的每个bean id前面加上一个常量字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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