我有这个枚举:
public enum SortEnum {
asc, desc;
}
Run Code Online (Sandbox Code Playgroud)
我想用作休息请求的参数:
@RequestMapping(value = "/events", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Event> getEvents(@RequestParam(name = "sort", required = false) SortEnum sort) {
Run Code Online (Sandbox Code Playgroud)
我发送这些请求时工作正常
/events
/events?sort=asc
/events?sort=desc
Run Code Online (Sandbox Code Playgroud)
但是当我发送时:
/events?sort=somethingElse
Run Code Online (Sandbox Code Playgroud)
我在控制台中得到500响应和此消息:
2016-09-29 17:20:51.600 DEBUG 5104 --- [ XNIO-2 task-6] com.myApp.aop.logging.LoggingAspect : Enter: com.myApp.web.rest.errors.ExceptionTranslator.processRuntimeException() with argument[s] = [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [com.myApp.common.SortEnum]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.myApp.common.SortEnum] for value 'somethingElse'; …Run Code Online (Sandbox Code Playgroud) 对于我的Spring-Boot应用程序,我通过@Configuration文件提供了RestTemplate,因此我可以添加合理的默认值(ex Timeouts).对于我的集成测试,我想模拟RestTemplate,因为我不想连接到外部服务 - 我知道期望的响应.我尝试在集成测试包中提供不同的实现,希望后者将覆盖实际的实现,但是反过来检查日志:真正的实现覆盖了测试.
如何确保TestConfig中的那个是使用的?
这是我的配置文件:
@Configuration
public class RestTemplateProvider {
private static final int DEFAULT_SERVICE_TIMEOUT = 5_000;
@Bean
public RestTemplate restTemplate(){
return new RestTemplate(buildClientConfigurationFactory());
}
private ClientHttpRequestFactory buildClientConfigurationFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(DEFAULT_SERVICE_TIMEOUT);
factory.setConnectTimeout(DEFAULT_SERVICE_TIMEOUT);
return factory;
}
}
Run Code Online (Sandbox Code Playgroud)
整合测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@WebAppConfiguration
@ActiveProfiles("it")
public abstract class IntegrationTest {}
Run Code Online (Sandbox Code Playgroud)
TestConfiguration类:
@Configuration
@Import({Application.class, MockRestTemplateConfiguration.class})
public class TestConfiguration {}
Run Code Online (Sandbox Code Playgroud)
最后是MockRestTemplateConfiguration
@Configuration
public class MockRestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
return Mockito.mock(RestTemplate.class)
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用spring-boot并添加spring-web依赖于maven pom,以便利用RestTemplate.
现在春天试图初始化一个EmbeddedServletContext.我该怎样预防呢?
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:183)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:156)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
... 8 more
Run Code Online (Sandbox Code Playgroud) 更新
我的问题是如何在spring boot中初始化一个孤立的spring webmvc web-app.隔离的Web应用程序应该:
WebSecurityConfigurer我们有多个web-apps,每个都以自己的方式执行安全性)和EmbeddedServletContainerCustomizer(设置servlet的上下文路径).进展
下面的配置类列在我的META-INF/spring.factories中.
以下策略不会导致运行web-mvc servlet.未设置上下文路径,也未定制安全性.我的预感是我需要包含某些webmvc bean来处理上下文并根据存在的bean自动配置 - 类似于我如何通过包含来启动基于引导的属性占位符配置PropertySourcesPlaceholderConfigurer.class.
@Configuration
@AutoConfigureAfter(DaoServicesConfiguration.class)
public class MyServletConfiguration {
@Autowired
ApplicationContext parentApplicationContext;
@Bean
public ServletRegistrationBean myApi() {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.setParent(parentApplicationContext);
applicationContext.register(PropertySourcesPlaceholderConfigurer.class);
// a few more classes registered. These classes cannot be added to
// the parent application context.
// includes implementations of
// WebSecurityConfigurerAdapter
// EmbeddedServletContainerCustomizer
applicationContext.scan(
// a few packages
);
DispatcherServlet ds = new DispatcherServlet();
ds.setApplicationContext(applicationContext);
ServletRegistrationBean …Run Code Online (Sandbox Code Playgroud) Abstract控制器类需要REST中的对象列表.使用Spring RestTemplate时,它不会将其映射到所需的类,而是返回Linked HashMAp
public List<T> restFindAll() {
RestTemplate restTemplate = RestClient.build().restTemplate();
ParameterizedTypeReference<List<T>> parameterizedTypeReference = new ParameterizedTypeReference<List<T>>(){};
String uri= BASE_URI +"/"+ getPath();
ResponseEntity<List<T>> exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
List<T> entities = exchange.getBody();
// here entities are List<LinkedHashMap>
return entities;
}
Run Code Online (Sandbox Code Playgroud)
如果我用,
ParameterizedTypeReference<List<AttributeInfo>> parameterizedTypeReference =
new ParameterizedTypeReference<List<AttributeInfo>>(){};
ResponseEntity<List<AttributeInfo>> exchange =
restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
Run Code Online (Sandbox Code Playgroud)
它工作正常.但不能放入所有子类,任何其他解决方案.
TestController.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void testThread(HttpServletResponse response) throws Exception {
testClass.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
TestClass.java
@Component
@Scope("prototype")
public class TestClass {
public TestClass() {
System.out.println("new test class constructed.");
}
public void doSomething() {
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我正在试图弄清楚TestClass当访问"xxx/test"时是否注入了新的."new test class constructed."只打印一次(第一次我触发"xxx/test"),而我期待它打印平等.那个卑鄙的@Autowired对象只能是@Singleton吗?@Scope工作怎么样?
编辑:
TestController.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void …Run Code Online (Sandbox Code Playgroud) 你能不能帮助我了解spring-boot-starter-web VS spring-boot-starter-web-services VS spring-boot-starter-jersey之间的区别
文档说Starter用于使用JAX-RS和Jersey构建RESTful Web应用程序.spring-boot-starter-web的替代品
谢谢
从一段时间以前,我正在按照Spring博客实施长轮询.
这里我的转换方法具有与以前相同的响应签名,但它现在使用长轮询而不是立即响应:
private Map<String, DeferredResult<ResponseEntity<?>>> requests = new ConcurrentHashMap<>();
@RequestMapping(value = "/{uuid}", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<?>> poll(@PathVariable("uuid") final String uuid) {
// Create & store a new instance
ResponseEntity<?> pendingOnTimeout = ResponseEntity.accepted().build();
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(TWENTYFIVE_SECONDS, pendingOnTimeout);
requests.put(uuid, deferredResult);
// Clean up poll requests when done
deferredResult.onCompletion(() -> {
requests.remove(deferredResult);
});
// Set result if already available
Task task = taskHolder.retrieve(uuid);
if (task == null)
deferredResult.setResult(ResponseEntity.status(HttpStatus.GONE).build());
else
// Done (or canceled): Redirect to …Run Code Online (Sandbox Code Playgroud) 我有一个简单的Spring Boot Web应用程序.我正在尝试从服务器接收一些数据.Controller返回一个集合,但浏览器接收空JSON - 大括号的数量等于来自服务器的对象数,但其内容为空.
@RestController
public class EmployeeController {
@Autowired
private EmployeeManagerImpl employeeManagerImpl;
@RequestMapping(path="/employees", method = RequestMethod.GET)
public Iterable<Employee> getAllEmployees() {
Iterable<Employee> employeesIterable = employeeManagerImpl.getAllEmployees();
return employeesIterable;
}
}
Run Code Online (Sandbox Code Playgroud)
该方法触发,浏览器显示:
在控制台中没有更多.有任何想法吗?
编辑:Employee.java
@Entity
public class Employee implements Serializable{
private static final long serialVersionUID = -1723798766434132067L;
@Id
@Getter @Setter
@GeneratedValue
private Long id;
@Getter @Setter
@Column(name = "first_name")
private String firstName;
@Getter @Setter
@Column(name = "last_name")
private String lastName;
@Getter @Setter
private BigDecimal salary;
public Employee(){
}
}
Run Code Online (Sandbox Code Playgroud) 我有这个控制器方法:
@PostMapping(
value = "/createleave",
params = {"start","end","hours","username"})
public void createLeave(@RequestParam(value = "start") String start,
@RequestParam(value = "end") String end,
@RequestParam(value = "hours") String hours,
@RequestParam(value = "username") String username){
System.out.println("Entering createLeave " + start + " " + end + " " + hours + " " + username);
LeaveQuery newLeaveQuery = new LeaveQuery();
Account account = accountRepository.findByUsername(username);
newLeaveQuery.setAccount(account);
newLeaveQuery.setStartDate(new Date(Long.parseLong(start)));
newLeaveQuery.setEndDate(new Date(Long.parseLong(end)));
newLeaveQuery.setTotalHours(Integer.parseInt(hours));
leaveQueryRepository.save(newLeaveQuery);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我向此端点发送帖子请求时,我得到以下信息
"{"timestamp":1511444885321,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.UnsatisfiedServletRequestParameterException","message":"Parameter conditions \"start, end, hours, username\" not met for actual request …Run Code Online (Sandbox Code Playgroud) spring-web ×10
java ×8
spring ×8
spring-boot ×6
spring-mvc ×4
json ×1
resttemplate ×1
spring-rest ×1
spring-test ×1
spring-ws ×1