简体   繁体   English

用于覆盖 XML 定义的 Bean 注释 - Spring

[英]Bean Annotation to override XML definition - Spring

My spring-boot application has another library project included as a dependency.我的 spring-boot 应用程序包含另一个库项目作为依赖项。 This library project has a spring.xml file where a number of beans defined.这个库项目有一个 spring.xml 文件,其中定义了许多 bean。 One of these beans has another external dependency injected which I don't need in my project.其中一个 bean 注入了另一个外部依赖项,我的项目中不需要它。 Hence this is throwing an error when I start my application.因此,当我启动我的应用程序时,这会引发错误。 I want to define the same bean in my application as a java config and make spring-boot ignore the specific bean from spring.xml file.我想在我的应用程序中定义相同的 bean 作为 java 配置,并使 spring-boot 忽略 spring.xml 文件中的特定 bean。 However I want all the other beans in spring.xml to be read.但是,我希望读取 spring.xml 中的所有其他 bean。

Define a bean in your local java config with the same name and type as the one inherited in the spring.xml file.在本地 java 配置中定义一个 bean,其名称和类型与 spring.xml 文件中继承的 bean 相同。

Annotate your bean with @Primary which will make yours used over the imported one.使用@Primary注释您的 bean,这将使您的 bean 用于导入的 bean。

Your application will still use the definitions of all the other beans you inherit.您的应用程序仍将使用您继承的所有其他 bean 的定义。

To prevent other defined beans loading that you do not actually need you have to change the bean creation to lazy configuration, that is, they only get created when explicitly used.为了防止加载其他您实际上不需要的已定义 bean,您必须将 bean 创建更改为延迟配置,也就是说,它们仅在显式使用时创建。

To do this in your main Spring boot class where the application is created, most likely annotated with @SpringBootApplication/ @Configuration/ @EnableAutoConfiguration/ @ComponentScan you should add @Lazy above it.要在创建应用程序的主 Spring 引导类中执行此操作,很可能用@SpringBootApplication/ @Configuration/ @EnableAutoConfiguration/ @ComponentScan注释,您应该在@Lazy上方添加@Lazy

Usually you would explicitly annotate the Bean in question but here it cannot be done as it is originating in a spring.xml file in a 3rd party jar.通常你会明确地注释有问题的 Bean,但在这里它不能完成,因为它起源于 3rd 方 jar 中的 spring.xml 文件。 The idea here is to cleanly state all beans are lazy from the highest point in the spring configuration.这里的想法是从 spring 配置的最高点干净地声明所有 bean 都是惰性的。

It seems that you want to include spring.xml from other jar and exclude a bean in the xml.似乎您想从其他 jar 中包含 spring.xml 并在 xml 中排除一个 bean。 I don't know spring framework provides some way.我不知道 spring 框架提供了一些方法。 I prefer to copy the spring.xml file to new project and remove the unnecessary bean.我更喜欢将 spring.xml 文件复制到新项目并删除不必要的 bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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