java - 使用 xml 配置休息 Spring bean
问题描述
我正在使用使用 xml 配置的 Rest Spring bean。我正在尝试使用 REST url 访问由 bean 初始化的变量。但我无法获取值。获取的值为空。无论如何初始化值并保持它们完整并在我使用网址拨打电话时访问它们。
请提出一些方法。
TIA
编辑:型号:
@Repository
public class Topic{
private Integer id;
private String name;
//Getter and setter with constructor
}
控制器类:
@RestController
@Singleton
public class TopicController{
@Autowired
private TopicService topicService;
public void setTopicService(TopicService topicService) {
this.topicService = topicService;
}
@RequestMapping("/topics")
public List<Topic> getAllTopics() {
System.out.println("in get all topics");
return topicService.getAllTopics();
}
}
服务类:
@Service
public class TopicService {
@Autowired
private List<Topic> allTopics ;
public TopicService() {
}
public List<Topic> getAllTopics() {
return allTopics;
}
public void setAllTopics(List<Topic> allTopics) {
this.allTopics = allTopics;
}
}
豆.xml
<bean name="topicService" id="topicService"
class="org.springtest.service.TopicService">
<property name="allTopics">
<list>
<bean class="org.springtest.model.Topic">
<property name="id" value="20" />
<property name="name" value="topic20" />
</bean>
<bean class="org.springtest.model.Topic">
<property name="id" value="30" />
<property name="name" value="Topic30" />
</bean>
</list>
</property>
</bean>
<bean id="topicController"
class="org.springtest.controller.TopicController"
scope="singleton">
<property name="topicService" ref="topicService"></property>
</bean>
的输出
/localhost:8080/topics
是:
{"id":null,"name":null}
主类:
public static void main(String[] args) {
SpringApplication.run(CourseApiApp.class, args);
ApplicationContext context = new
ClassPathXmlApplicationContext("main/resources/Bean.xml");
TopicController tc= new TopicController();
System.out.println(tc.getAllTopics().size());// throwing nullpointerexception as topicService is null
}
解决方案
我建议你看看泽西岛。这是一个 REST 框架,在我看来是最好的框架之一。请务必使用 Jersey 最新版本的快照(我相信它是第 3 版),因为它将完全支持 Spring。
它的用法很简单。方法控制器将有 5 行顶部。它还鼓励用户使用 RESTful API 的最佳实践。例如在成功的帖子上定义位置标头,引用集合中的分页的链接标头等等。
在您的项目中使用 Maven 或 Gradle,集成 Jersey 将花费您 5 分钟。
我在 Spring 上使用它,因为它的唯一目的是实现 REST API,而 Spring 只是将它作为一个特性。
对于我缺乏解决方案,我深表歉意,请问我是否需要帮助开始。
安德烈斯
推荐阅读
- algorithm - 是否有系统的方法将递归函数重写为尾递归函数?
- html - 选择标签 html 中的值不会添加到数据库中
- xamarin.ios - 集合视图布局问题
- python - 从命令行运行脚本时视频捕获失败
- html - Bootstrap 3 工具提示删除标题中内容的换行符\n
- python - 正则表达式:将斜体和 b_o_l_d 转换为 *italics* 和 **bold**
- symfony - 同一类型实体上的 Symfony 多对多关系
- php - 基于许多关系链接的Gridview过滤器
- css - 无法访问 node.js html 文件中的 CSS
- docker - 无法从 docker 容器访问 localhost:3330