Spring Boot注解 之 @Import

本文的示例代码参考Import

目录

开始

spring init -dweb --build gradle Import
# cd Import
vim src/main/java/com/example/Import/HelloController.java
package com.example.Import;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/")
    public String hello() {
        return "HelloController";
    }
}
  • 测试
./gradlew bootrun

curl localhost:8080 # 返回"HelloController"

@Import

mkdir -p src/main/java/com/example/AnotherPackage
vim src/main/java/com/example/AnotherPackage/Engine.java
package com.example.AnotherPackage;

public class Engine {
    private String model;

    Engine(String model) {
        this.model = model;
    }

    public void work() {
        System.out.println(this.model + " engine work");
    }
}
vim src/main/java/com/example/AnotherPackage/EngineConfiguration.java
package com.example.AnotherPackage;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EngineConfiguration{
    @Bean
    public Engine getEngine() {
        return new Engine("Ferrari");
    }
}
vim src/main/java/com/example/Import/HelloController.java
# 省略了未修改代码
public class HelloController {

    @Autowired
    private Engine engine;

    @RequestMapping("/")
    public String hello() {
        engine.work();
        return "HelloController";
    }
}
  • 测试
./gradlew bootrun
***************************
APPLICATION FAILED TO START
***************************

Description:

Field engine in com.example.Import.HelloController required a bean of type 'com.example.AnotherPackage.Engine' that could not be found.

Action:

Consider defining a bean of type 'com.example.AnotherPackage.Engine' in your configuration.
vim src/main/java/com/example/Import/DemoApplication.java
package com.example.Import;

import com.example.AnotherPackage.EngineConfiguration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@EnableAutoConfiguration
@ComponentScan
@Import(EngineConfiguration.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • 测试
./gradlew bootrun

curl localhost:8080 # 打印"Ferrari engine work" + 返回"HelloController"

参考

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容