我有一个非常简单的项目。
它有主类:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller :
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Controller {
@Autowired
MyService myService;
@RequestMapping("/application")
public String getApp(ModelMap model) {
return "application";
}
@RequestMapping("/application/home")
public String do(@RequestParam(value="input", required=false) String input, ModelMap model) {
if (!StringUtils.isEmpty(input)) {
model.addAttribute(INPUT_ATT, input);
model.addAttribute(OUTPUT_ATT, myService.do(input));
}
return "home";
}
}
还有一个服务(接口(interface)、实现):
package com.example;
public interface MyService {
String do(String input);
}
.
package com.example;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImpl implements MyService {
@Override
public String do(String input) {
return "result";
}
}
不幸的是,MyServiceImpl 的实例没有被注入(inject)到 Controller 类中的 myService 变量中。
我应该怎么做才能解决这个问题?
关于,
最佳答案
您的代码未编译,因为“do”是关键字。但除此之外,您的代码应该没问题。我也尝试使用 SpringBoot 稍作修改
申请
@SpringBootApplication
public class Application {
/**
* Run the Web Application using built-in Tomcat server.
* This is used for testing only
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller
@RestController
public class HelloworldController {
@Autowired
private IHelloworldHelper helper;
@RequestMapping("/hello")
public Helloworld hello(String name) {
return new Helloworld(1, helper.doAction(name));
}
}
助手
@Service
public class HelloworldHelper implements IHelloworldHelper {
@Override
public String doAction(String name) {
return String.format("Hi %s!", name);
}
}
public interface IHelloworldHelper {
public String doAction(String name);
}
模型
public class Helloworld {
private long id;
private String content;
public Helloworld(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
关于java - 简单 Spring 应用程序中的依赖注入(inject)不起作用(将服务注入(inject) Controller 变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004718/