无法创建自定义 Spring Boot Starter/AutoConfiguration

him*_*hra 2 java vmware spring spring-boot

自定义启动项目命名为:hello-service-spring-boot-start

项目目录结构为: hello-service-spring-boot-start目录结构

在 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 https://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>3.0.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.javadevjournal</groupId>
    <artifactId>hello-service-spring-boot-start</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-service-spring-boot-start</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


Run Code Online (Sandbox Code Playgroud)

在 Starter 类或 HelloServiceSpringBootStartApplication.java 中

package com.javadevjournal.helloservicespringbootstart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloServiceSpringBootStartApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloServiceSpringBootStartApplication.class, args);
        System.out.println("hello-service-spring-boot-start-application started...");
    }

}

Run Code Online (Sandbox Code Playgroud)

在HelloService.java中

package com.javadevjournal.helloservicespringbootstart.service;

public interface HelloService {
    void sayHello();
}

Run Code Online (Sandbox Code Playgroud)

在HelloServiceImpl.java中

package com.javadevjournal.helloservicespringbootstart.service;

public class HelloServiceImpl implements HelloService {
    @Override
    public void sayHello() {
        System.out.println("Hello from the default starter hello service");
    }
}

Run Code Online (Sandbox Code Playgroud)

在HelloServiceAutoConfiguration.java中

package com.javadevjournal.helloservicespringbootstart.config;

import com.javadevjournal.helloservicespringbootstart.service.HelloService;
import com.javadevjournal.helloservicespringbootstart.service.HelloServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public HelloService helloService() {
        return new HelloServiceImpl();
    }
}

Run Code Online (Sandbox Code Playgroud)

在 spring.factories 中

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.javadevjournal.helloservicespringbootstart.HelloServiceSpringBootStartApplication
Run Code Online (Sandbox Code Playgroud)

然后,我运行 mvn install 来创建 jar 文件或构建上述启动器。

我在上面使用启动器的项目名为:custom-app

项目目录结构为: custom-app项目目录结构

在 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 https://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>3.0.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.javadevjournal</groupId>
    <artifactId>custom-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>custom-app</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.javadevjournal</groupId>
            <artifactId>hello-service-spring-boot-start</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Run Code Online (Sandbox Code Playgroud)

在 Starter 类或 CustomAppApplication.java 类中

package com.javadevjournal.customapp;

import com.javadevjournal.helloservicespringbootstart.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CustomAppApplication implements CommandLineRunner {

    @Autowired
    HelloService helloService;

    public static void main(String[] args) {
        SpringApplication.run(CustomAppApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        helloService.sayHello();
    }
}

Run Code Online (Sandbox Code Playgroud)

输出:控制台。

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.2)

2023-02-01T21:49:48.215+05:30  INFO 11332 --- [  restartedMain] c.j.customapp.CustomAppApplication       : Starting CustomAppApplication using Java 18.0.2.1 with PID 11332 (G:\Java\IntelliJ Workspace\Learning\Spring Boot By Raghu\CustomStarterAutoConfigurationActual\custom-app\target\classes started by himan in G:\Java\IntelliJ Workspace\Learning\Spring Boot By Raghu\CustomStarterAutoConfigurationActual\hello-service-spring-boot-start)
2023-02-01T21:49:48.217+05:30  INFO 11332 --- [  restartedMain] c.j.customapp.CustomAppApplication       : No active profile set, falling back to 1 default profile: "default"
2023-02-01T21:49:48.261+05:30  INFO 11332 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-02-01T21:49:48.623+05:30  WARN 11332 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAppApplication': Unsatisfied dependency expressed through field 'helloService': No qualifying bean of type 'com.javadevjournal.helloservicespringbootstart.service.HelloService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2023-02-01T21:49:48.629+05:30  INFO 11332 --- [  restartedMain] .s.b.a.l.ConditionEvaluationReportLogger : 

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-02-01T21:49:48.653+05:30 ERROR 11332 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field helloService in com.javadevjournal.customapp.CustomAppApplication required a bean of type 'com.javadevjournal.helloservicespringbootstart.service.HelloService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.javadevjournal.helloservicespringbootstart.service.HelloService' in your configuration.


Process finished with exit code 0

Run Code Online (Sandbox Code Playgroud)

截屏。 输出:控制台

我正在尝试在 Spring Boot 中创建自定义启动项目并在另一个项目中使用它。但我收到错误,这说明在自定义启动器中创建的 bean 未初始化。我期望在控制台中打印启动程序的问候消息。

Dir*_*yne 9

spring-boot- 3不再用于spring.factories注册自动配置类。

创建一个名为org.springframework.boot.autoconfigure.AutoConfiguration.importsin 文件夹的文件META-INF/spring,您可以在其中放置(所有)Configuration类。

在你的情况下,这将是

/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

com.javadevjournal.helloservicespringbootstart.config.HelloServiceAutoConfiguration
Run Code Online (Sandbox Code Playgroud)

请注意,这不应该是 SpringBootApplication

参考: 创建您自己的自动配置