【发布时间】:2019-05-30 08:48:51
【问题描述】:
我想在 java rest 项目中使用 spring @Autowired。在过去的几天里,我正在尝试使用 java 配置设置一个简单的 spring java 项目,而没有明确的 bean 配置来检查该功能。但我无法让它工作。我可能遗漏了一些基本的东西。
到目前为止,我在网络和本网站上找到的方法都没有解决我的问题。我也找不到我想要达到的目标的样本。这主要是由于网络上存在大量不同的 spring 版本和方法。
这是一个尽可能简单的 Java Spring 休息示例。我添加了一些关于我如何解释 spring 注释的 cmets,因为我也可能在这里犯错:
应用基类
package restoverflow;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/")
public class App extends Application {
}
配置类
package restoverflow;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //this is a configuration class and also found by spring scan
@ComponentScan //this package and its subpackages are being checked for components and its subtypes
public class AppConfig {
}
一些波乔
package restoverflow;
public class Pojo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
一项服务
package restoverflow;
import org.springframework.stereotype.Service;
@Service //this is a subtype of component and found by the componentscan
public class PojoService {
public Pojo getPojo(){
Pojo pojo = new Pojo();
pojo.setName("pojoName");
return pojo;
}
}
最后是应该完成服务自动装配的资源
package restoverflow;
import javax.ws.rs.GET;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/resource")
@Controller //this is a subtype of component and found by the componentscan
public class Resource {
@Autowired //this tells to automatically instantiate PojoService with a default contructor instance of PojoService
private PojoService pojoService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Pojo getPojo() {
return pojoService.getPojo();
}
}
波姆:
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
...
我希望 pojoService 被实例化。但我得到一个 NullPointerException。
【问题讨论】:
标签: java spring configuration autowired