我无法理解为什么我的 BeanRealApplication
没有注册/找到。
文件 DemoApplication.java:
package com.example.simple;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class DemoApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext();
ctx.refresh();
RealApplication app = ctx.getBean(RealApplication.class);
app.run();
ctx.close();
}
}
文件 RealApplication.java:
package com.example.simple;
import org.springframework.stereotype.Component;
@Component
public class RealApplication
{
public void run()
{
System.out.println("Hello World!");
}
}
然而,奇怪的是,这段代码有效:
文件 DemoApplication.java:
package com.example.simple;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class DemoApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext("com.example.simple");
RealApplication app = ctx.getBean(RealApplication.class);
app.run();
ctx.close();
}
}
RealApplication 类没有改变。
输出是:
Hello World!
我的 maven pom.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>simple-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
出于某种奇怪的原因,当我只使用注释时,组件扫描并没有拾取 RealApplication Bean @SpringBootApplication
,即使这两个类是同一个包。
但是当我在构造函数中指定要扫描的包时,它能够找到它AnnotationConfigApplicationContext