下面代码会出现什么问题,如何解决? Java @RestController @RequestMapping("/api") public class MyController { @Autowired private MyService service; @GetMapping("/foo") public String foo() { return service.doSomething(); } } @Service public class MyService { @Autowired private SomeOtherService otherService; public String doSomething() { return otherService.getSomething(); } } public class SomeOtherService { public String getSomething() { return "something"; } }
时间: 2023-06-05 12:04:25 浏览: 42
这段代码的问题是MyService类没有使用@Service注解进行标注,Spring容器无法识别该类为一个Bean,无法进行自动注入。要解决这个问题,只需要在MyService类上添加@Service注解即可。
相关问题
@PostMapping("/postPath") public ResultBean<String> postPath(@RequestBody Map<String,Object> data) { String path = (String) data.get("path"); String taskResolvePath = path+"/"+"TaskResolve.xml"; // TaskResolve taskResolve = syslinkProjectService.parseXml(path1); return ResultBean.ofSuccess(taskResolvePath); }怎么拆成controller层和service层代码
Controller层代码:
```
@RestController
@RequestMapping("/api")
public class MyController {
@Autowired
private MyService myService;
@PostMapping("/postPath")
public ResultBean<String> postPath(@RequestBody Map<String,Object> data) {
String path = (String) data.get("path");
String taskResolvePath = myService.getTaskResolvePath(path);
return ResultBean.ofSuccess(taskResolvePath);
}
}
```
Service层代码:
```
@Service
public class MyService {
public String getTaskResolvePath(String path) {
String taskResolvePath = path + "/" + "TaskResolve.xml";
// TaskResolve taskResolve = syslinkProjectService.parseXml(path1);
return taskResolvePath;
}
}
```
其中,Controller层通过@Autowired注入Service层,调用Service层中的方法来完成业务逻辑。在Service层中实现具体的业务逻辑,将复杂的业务代码从Controller层中抽离出来,使得Controller层更加简洁、易于维护。
不是spring托管的对象,怎么用@value获取yml配置
如果对象不是 Spring 托管的,你可以使用 `@ConfigurationProperties` 注解来将 YAML 配置文件中的属性映射到该对象中。具体步骤如下:
1. 在类上加上 `@ConfigurationProperties` 注解,并指定其对应的前缀,如:
```java
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String name;
private int age;
// 省略 getter 和 setter 方法
}
```
2. 在 YAML 配置文件中添加对应的属性:
```yaml
myconfig:
name: "John"
age: 18
```
3. 在需要使用该对象的地方直接注入即可,如:
```java
public class MyService {
@Autowired
private MyConfig myConfig;
public void printConfig() {
System.out.println("name: " + myConfig.getName() + ", age: " + myConfig.getAge());
}
}
```
注意:如果你的对象不是 Spring 托管的,则需要手动创建该对象并将其注入到需要使用它的类中,如:
```java
public class MyController {
private MyConfig myConfig;
public MyController() {
myConfig = new MyConfig();
}
@PostConstruct
public void init() {
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("config.yml"));
PropertySource<?> propertySource = new PropertiesPropertySource("yaml", yaml.getObject());
Binder binder = new Binder(propertySource);
myConfig = binder.bind("myconfig", MyConfig.class).get();
}
@RequestMapping("/config")
public String getConfig() {
return "name: " + myConfig.getName() + ", age: " + myConfig.getAge();
}
}
```