简体   繁体   English

插件 Class 的依赖注入

[英]Dependency Injection for Plugin Class

I have a class in a jar file like我在 jar 文件中有一个 class

Class A {
  B b;
  C c;
//setter based injection
}

Now I want to create a bean of A in a different project.现在我想在另一个项目中创建一个 A 的 bean。 But I don't have any main class to configure the Spring application.但是我没有任何主要的 class 来配置 Spring 应用程序。 I have a plugin in my pom.xml which calls Class D in my project.我的 pom.xml 中有一个插件,它在我的项目中调用 Class D。 If I create a bean with the new keyword all the autowired beans in the jar will not be available.如果我使用new关键字创建一个 bean,则 jar 中的所有自动装配的 bean 都将不可用。 please suggest any methods to do this.请提出任何方法来做到这一点。

Note: This is a Spring application, Not Spring boot.注意:这是 Spring 应用程序,而不是 Spring 启动。

So that you are able to autowire a bean you need to register that bean as a Spring-managed bean.为了能够自动装配 bean,您需要将该 bean 注册为 Spring 管理的 bean。 You can do that in multiple ways, being the following ones the simplest ones:您可以通过多种方式做到这一点,以下是最简单的方式:

1) @Component annotation 1)@Component注解

If you annotate A with @Component Spring will create an instance of the class and register it as a Spring-managed bean:如果您使用@Component Spring 注释A将创建 class 的实例并将其注册为 Spring 管理的 bean:

@Component
Class A {
  B b;
  C c;
//setter based injection
}

2) @Bean annotation 2)@Bean注解

Another way to register a Bean is using a Configuration class and the @Bean annotation:注册 Bean 的另一种方法是使用配置 class 和@Bean注释:

@Configuration
public class AppConfig {
    @Bean
    public A a() {
        return new A();
    }
}

If I understood correctly your use case, you will need to use option 2).如果我正确理解您的用例,您将需要使用选项 2)。

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

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