Skip to content

Instantly share code, notes, and snippets.

@dennysfredericci
Last active November 15, 2019 10:57
Show Gist options
  • Save dennysfredericci/5684dbc327e49a409ea65c3496b3660c to your computer and use it in GitHub Desktop.
Save dennysfredericci/5684dbc327e49a409ea65c3496b3660c to your computer and use it in GitHub Desktop.
Example of Spring Bean in a Request Scope
package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class FeiController {
@Autowired
private FeiBean feiBean;
@GetMapping("/")
public void getFei() {
System.out.println(feiBean);
}
}
@Configuration
class FeiConfig {
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public FeiBean feiBean(@Autowired HttpServletRequest request) {
final Map<String, String> headers = Collections.list(request.getHeaderNames()).stream()
.collect(Collectors.toMap(headerName -> headerName, request::getHeader));
final String name = "fei-" + new Random().ints(1).findAny().getAsInt();
return new FeiBean(name, headers);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class FeiBean {
private String name;
private Map<String, String> headers;
}
@gajjardarshithasmukhbhai

hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment