【发布时间】:2016-04-25 20:23:35
【问题描述】:
我有一个在 Spring 中自动装配的普通 POJO,其属性似乎保持不变。
我发现快乐的路径没问题 - 设置 bean 属性然后返回,但是当我不在快乐的路径上并且我不再希望设置属性(在本例中为 responseCode)时,我发现它仍然是设置为之前的值(调用成功时)。
我希望这个值不被设置并且等于我当前在模型中指定的值。
我有以下 POJO Prototype bean
package com.uk.jacob.model;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class Website {
public String url;
public boolean response;
public int responseCode = 0;
}
我在服务类中设置它的信息
package com.uk.jacob.service;
import java.net.HttpURLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.uk.jacob.adapter.HttpAdapter;
import com.uk.jacob.model.Website;
@Component
public class PingerService {
@Autowired
HttpAdapter httpAdapter;
@Autowired
Website website;
public Website ping(String urlToPing) {
website.url = urlToPing;
try {
HttpURLConnection connection = httpAdapter.createHttpURLConnection(urlToPing);
website.response = true;
website.responseCode = connection.getResponseCode();
} catch (Exception e) {
website.response = false;
}
return website;
}
}
从 RestController 调用
package com.uk.jacob.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.uk.jacob.model.Website;
import com.uk.jacob.service.PingerService;
@RestController
@RequestMapping("api/v1/")
public class PingController {
@Autowired
PingerService pingerService;
@RequestMapping(value = "ping", method = RequestMethod.GET)
public Website getPing(@RequestParam String url){
return pingerService.ping(url);
}
}
【问题讨论】:
标签: java spring spring-mvc