Last active
November 15, 2019 10:57
-
-
Save dennysfredericci/5684dbc327e49a409ea65c3496b3660c to your computer and use it in GitHub Desktop.
Example of Spring Bean in a Request Scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello