2

我正在使用自定义AbstractProcessor来生成一些类。我尝试生成 Spring 组件 A 和 B,其中 B“自动装配”A。输出类看起来类似于:

@Component
public class ClassA {
    @Bean
    public MyBean getMyBean() {
        return new MyBean();
    }
}
@Component
public class ClassB {
    @Autowired
    private ClassA myClassA;

    private MyBean myBean;

    public ClassB() {
        this.myBean = myClassA.getMyBean();
    }
}

但是 autowiredmyClassA是空的。我怀疑春季扫描是在我的课程开始之前发生的。

当我运行时,mvn clean install 我有

...
[INFO] --- spring-boot-maven-plugin:2.0.1.RELEASE:repackage (default) @ main ---

[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ main ---
[INFO] Installing C:\Users\me\Documents\kubernetes\spring\testproject2\main\target\main-1.0-SNAPSHOT.jar to C:\Users\me\.m2\repository\be\mycompany\main\1.0-SNAPSHOT\main-1.0-SNAPSHOT.jar
[INFO] Installing C:\Users\me\Documents\kubernetes\spring\testproject2\main\pom.xml to C:\Users\me\.m2\repository\be\mycompany\main\1.0-SNAPSHOT\main-1.0-SNAPSHOT.pom

spring-boot-maven-plugin这表明maven-install-plugin. 这是我的“注释处理器”项目中使用的插件配置:

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <showWarnings>true</showWarnings>
            </configuration>
            <executions>
                <execution>
                    <id>default-compile</id>
                    <configuration>
                        <compilerArgument>-proc:none</compilerArgument>
                        <includes>
                            <include>be/mycompany/testproject2/dbgenerator/processing/DatabaseAnnotationProcessor.java</include>
                        </includes>
                    </configuration>
                </execution>
                <execution>
                    <id>compile-project</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

关于如何确保我生成的组件可以自动装配的任何提示?

谢谢。

4

1 回答 1

0

在这种情况下,您应该使用 Class B 的构造函数来确保 Class A 存在:

@Component
public class ClassB {
    @Autowired
    private ClassA myClassA;

    private MyBean myBean;

    public ClassB(ClassA myClassA) {
        this.myBean = myClassA.getMyBean();
        this.myClassA= myClassA;
    }
}
于 2019-12-18T13:08:36.550 回答