【发布时间】:2018-01-18 08:50:28
【问题描述】:
我正在尝试创建一个简单的 Spring Boot 应用程序,它将名称作为 URL 中的参数(例如 http://localhost:8080/hello/john)并以英语或德语问候页面(“Hello John”或“Hallo John ")。
我在 Ubuntu 14.04 下使用 IntelliJ Idea 2017.3.3。
为此,我创建了一个 Spring Intializr 项目和一个名为 GreetingService 的接口:
package com.springboot.configuration.service;
import org.springframework.stereotype.Component;
@Component
public interface GreetingService {
String sayHello(String name);
}
这个接口将在两个类中实现,GrretingServiceEnglish 和 GreetingServiceGerman 如下:
package com.springboot.configuration.service;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("english")
public class GreetingServiceEnglish implements GreetingService{
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
和
package com.springboot.configuration.service;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("german")
public class GreetingServiceGerman implements GreetingService{
@Override
public String sayHello(String name) {
return "Hallo " + name;
}
}
要选择必须使用哪一个,在 application.properties 中有一个条目:
spring.profiles.active="english"
在控制器中我进行自动装配:
package com.springboot.configuration.controller;
import com.springboot.configuration.service.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/", method = RequestMethod.GET)
public class GreetingController {
@Autowired
private GreetingService greetingService;
@RequestMapping(path = "hello/{name}")
public String sayHello(@PathVariable(name = "name") String name){
return greetingService.sayHello(name);
}
}
应用程序是:
package com.springboot.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProfilesApplication {
public static void main(String[] args) {
SpringApplication.run(ProfilesApplication.class, args);
}
}
当我运行应用程序时出现错误:
com.springboot.configuration.controller.GreetingController 中的字段 greetingService 需要一个“com.springboot.configuration.service.GreetingService”类型的 bean,但找不到。
怎么了?你能帮帮我吗?
【问题讨论】:
-
如何配置组件扫描?
-
有更好的方法来处理依赖于语言的文本
-
@SpringBootApplication 注解在哪里?在哪个包里?在应用程序日志中,您可以验证活动配置文件,搜索此行“--- 以下配置文件处于活动状态:”
-
当然,但是我正在学习spring boot的基础,所以这永远不会是生产代码,只是学习。
-
我已经添加了我的 ProfileApplication.java
标签: java spring spring-boot autowired