本文的示例代码参考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"