首页 > 解决方案 > 使用 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
}

标签: javaxmlspringspring-mvcspring-boot

解决方案


我建议你看看泽西岛。这是一个 REST 框架,在我看来是最好的框架之一。请务必使用 Jersey 最新版本的快照(我相信它是第 3 版),因为它将完全支持 Spring。

它的用法很简单。方法控制器将有 5 行顶部。它还鼓励用户使用 RESTful API 的最佳实践。例如在成功的帖子上定义位置标头,引用集合中的分页的链接标头等等。

在您的项目中使用 Maven 或 Gradle,集成 Jersey 将花费您 5 分钟。

我在 Spring 上使用它,因为它的唯一目的是实现 REST API,而 Spring 只是将它作为一个特性。

对于我缺乏解决方案,我深表歉意,请问我是否需要帮助开始。

安德烈斯


推荐阅读